Django 模板:表单字段名称作为变量? [英] Django Templates: Form field name as variable?
问题描述
如何使这个循环打印表单字段,其中 XXXXXXXX 是 ticket.id 的值?
How can I make this loop to print form fields where XXXXXXXX is the value of ticket.id?
{% for ticket in zone.tickets %}
{{ ticket.id }}: {{ form.ticket_count_XXXXXXXX }}
{% endfor %}
所以输出是这样的......
So the output to be something like this...
1: <input ... name="ticket_count_1">
10: <input ... name="ticket_count_10">
12: <input ... name="ticket_count_12">
3: <input ... name="ticket_count_3">
推荐答案
你不能在 django 模板中传递参数,所以不能.
You can't pass arguments in the django template, so no.
你需要实现一个模板标签(更痛苦)或过滤器,或者在你的视图中建立从 ticket
到 formfield
的关联(我会推荐).
You'd need to implement a template tag (more of a pain) or filter, or make the association from ticket
to formfield
in your view (what I would recommend).
因为我实际上并不知道 ticket
和您的表单字段之间的关系,所以我不知道最好的方法是什么,但是根据您的信息,这将有效"已经提供.
Since I don't actually know the relationship between ticket
and your form fields, I can't tell what the best method is, but this would 'just work' based on the info you've provided.
# view
form = MyForm()
for ticket in zone.tickets:
ticket.form_field = form['ticket_count_' + str(ticket.id)]
# template
{% for ticket in zone.tickets %}
{{ ticket.id }} : {{ ticket.form_field }}
{% endfor %}
这篇关于Django 模板:表单字段名称作为变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!