Django模板:表单字段名称作为变量? [英] Django Templates: Form field name as variable?

查看:74
本文介绍了Django模板:表单字段名称作为变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使此循环打印表格字段,其中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.

您需要实现一个模板标签(更多的是痛苦)或过滤,或者从票据 to 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).

由于我实际上不知道票之间的关系和您的表单字段,我无法确定最好的方法是什么,但这将根据您提供的信息正常工作。 p>

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆