我在弄清楚如何使用 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'}]}
然后我将此数据传递到我的模板,我需要执行以下操作:
- 创建表单
- 预先填充一些与“locations”中的值相关的表单字段
- 如果我的“位置”少于 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) 添加缺失的空白表单字段对的想法将不胜感激。
最佳答案
if info['user'] == username:
locations = (json.loads(info['locations']) +
[{'place': '', 'description': ''}] * 5)[:5]
return {'date': info['date'], 'locations': locations}
关于python - Django 模板中的动态表单字段生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2066181/