在 django 中引用模板中的动态数量的字段
一切都很简单。我有这样的形式:
class add_basketForm(forms.Form):
def __init__(self, selected_subunits, *args, **kwargs):
self.selected_subunits = selected_subunits
super(add_basketForm, self).__init__(*args, **kwargs)
for subunit in self.selected_subunits:
self.fields['su%d' % (subunit['unit__id'])] = forms.IntegerField()
亚基的数量未知。我想使用这样的东西(你明白了):
{% for unit in selected_subunits %}
{{ form.su%s }} % (unit.unit__id)
{% endfor %}
但这当然行不通。我的问题是如何在 Django 模板语言中引用这些表单字段?
It is all very simple. I have this form:
class add_basketForm(forms.Form):
def __init__(self, selected_subunits, *args, **kwargs):
self.selected_subunits = selected_subunits
super(add_basketForm, self).__init__(*args, **kwargs)
for subunit in self.selected_subunits:
self.fields['su%d' % (subunit['unit__id'])] = forms.IntegerField()
The number of subunits are unknown. I would like to use something like this (you get the idea):
{% for unit in selected_subunits %}
{{ form.su%s }} % (unit.unit__id)
{% endfor %}
But of course that doesn't work. My question is how do I reference those formfields in Django template language?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了访问动态字段实例的 BoundField 实例,您可以访问 渲染字段所需的所有属性和方法,需要使用
form.fieldname
的形式访问字段对象而不是form.fields[fieldname]
下面是表单类的潜在重构:
然后在模板中,您应该能够像通常期望的那样通过访问
form 来迭代字段。 su_fields
:(几个小时以来我一直在努力解决同样的问题。感谢 卡尔·迈耶的回答和这篇文章关于 Jacob Kaplan-Moss 的动态表单生成,为我指明了正确的方向。)
In order to access the BoundField instances for your dynamic field instances, which is what gives you access to all of the attributes and methods necessary to render the field, you need to access the field objects using the form of
form.fieldname
rather thanform.fields[fieldname]
Here's a potential refactoring of your form class:
Then in your template, you should be able to iterate over the fields as you would normally expect by accessing
form.su_fields
:(I had been struggling with this same problem for several hours. Thanks to this answer from Carl Meyer and this article on dynamic form generation from Jacob Kaplan-Moss for pointing me in the right directions.)
将这些字段分组到一个附加列表中,然后简单地迭代该列表。
在
__init__
中:在模板中:
Group those fields in an additional list and then simply iterate over this list.
In
__init__
:In template:
为了纠正 gruszczy 的答案,这段代码对我有用:
在表单的
__init__
中:在模板中:
To correct gruszczy's answer, this code worked for me:
In
__init__
of your form:In your template: