【发布时间】:2010-01-14 17:38:26
【问题描述】:
我在弄清楚如何用 Django 和(可能)用 Python 方式解决这个问题时遇到了问题。我正在向包含以下值的模板发送哈希
{'date': '2009-12-30', 'locations': [{u'lat': 43.514000000000003, u'lng': -79.844032999999996, u'place': u'1053 Bowring Cres, Milton, ON L9T, CA', u'description': u'Home base'}, {u'lat': 43.730550000000001, u'lng': -79.805334000000002, u'place': u'50 Dawnridge Trl, Brampton, ON L6Z, CA', u'description': u'Southfork'}]}
然后我将此数据传递给我的模板,我需要执行以下操作:
- 创建表单
- 预填充许多与“位置”内的值相关的表单字段
- 如果我的“位置”少于 5 个,请添加一些空白表单字段,直到我有 5 个
这是提取并生成数据的代码——它从 CouchDB 中获取信息
def get_by_id(self, username, search_id):
if username and search_id:
info = db.get(search_id)
if info['user'] == username:
return {'date': info['date'],
'locations': json.loads(info['locations'])}
我想我可以以某种方式操纵 info['locations'] 中的内容以添加 ID,但我一直在努力理解 Python 如何处理对 JSON 的迭代。
这是我用来创建表单的模板中的代码。 my_search 包含我上面显示的数据
<form method="post" action="/locations">
<input type="hidden" name="search_id" value="{{ search_id }}">
<table>
<tr>
<th>Location</th>
<th>Description</th>
</tr>
{% for location in my_search.locations %}
<tr>
<td><input type="text" name="location" id="id_location"
value="{{ location.place }}"></td>
<td><input type="text" name="description" id="id_description"
value="{{ location.description }}"></td>
</tr>
{% endfor %}
</table>
<input type="submit" value="Update Plan">
</form>
如果我的位置少于 5 个,如何 (a) 轻松添加唯一 ID 和 (b) 添加缺少的空白表单字段对,我们将不胜感激。
【问题讨论】: