且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django 模板:表单字段名称作为变量?

更新时间:2023-02-19 10:39:04

你不能在 django 模板中传递参数,所以不能.

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

你需要实现一个模板标签(更痛苦)或过滤器,或者在你的视图中建立从 ticketformfield 的关联(我会推荐).

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