[英]Dynamic form field generation in Django templates
I am having a problem figuring out how to solve this problem the Django and (probably) the Python way. 我有一个问题,弄清楚如何解决Django和(可能)Python方式的这个问题。 I am sending a hash to a template that contains the following values
我将散列发送到包含以下值的模板
{'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'}]}
I then pass this data to my template and I need to do the following: 然后我将此数据传递给我的模板,我需要执行以下操作:
Here's the code that pulls in and generates the data -- it grabs info from CouchDB 这是拉入并生成数据的代码 - 它从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'])}
I suppose I could somehow manipulate what is in info['locations'] to add in an ID, but I've been struggling with understanding how Python handles iterating through the JSON. 我想我可以以某种方式操纵info ['locations']中的内容来添加ID,但我一直在努力理解Python如何处理迭代JSON。
Here's the code in template I'm using to create the form. 这是我用来创建表单的模板中的代码。 my_search contains the data I've shown above
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>
Thoughts on how to (a) easily add in a unique ID and (b) add in the missing blank form field pairs if I have less than 5 locations would be greatly appreciated. 关于如何(a)轻松添加唯一ID以及(b)如果我有少于5个位置添加缺少的空白表单字段对的想法将非常感激。
if info['user'] == username:
locations = (json.loads(info['locations']) +
[{'place': '', 'description': ''}] * 5)[:5]
return {'date': info['date'], 'locations': locations}
(一种)
id="id_location_{{ forloop.counter }}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.