Django Templates: Form field name as variable?

我的未来我决定 提交于 2019-12-19 11:21:10

问题


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">

回答1:


You can't pass arguments in the django template, so no.

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).

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 %}


来源:https://stackoverflow.com/questions/4993625/django-templates-form-field-name-as-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!