在django中引用模板中的动态数量的字段

时间:2011-01-05 12:38:46

标签: django templates forms dynamic

这一切都很简单。我有这样的表格:

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模板语言中引用这些表单域?

3 个答案:

答案 0 :(得分:7)

为了访问动态字段实例的BoundField实例,这使您可以访问all of the attributes and methods necessary to render the field,您需要使用form.fieldname而不是{{1}的形式访问字段对象}}

以下是您的表单类的潜在重构:

form.fields[fieldname]

然后在您的模板中,您应该能够像访问class add_basketForm(forms.Form): def __init__(self, selected_subunits, *args, **kwargs): super(add_basketForm, self).__init__(*args, **kwargs) for subunit in self.selected_subunits: self.fields['su%d' % (subunit['unit__id'])] = forms.IntegerField() def su_fields(self): for name in self.fields: if name.startswith('su'): yield(self[name]) 时通常所期望的那样遍历字段:

form.su_fields

(几个小时以来,我一直在努力解决同样的问题。感谢this answer from Carl Meyerthis article on dynamic form generation from Jacob Kaplan-Moss让我指向了正确的方向。)

答案 1 :(得分:4)

将这些字段分组到一个附加列表中,然后简单地遍历此列表。

__init__

self.subunit_list = []
for subunit in self.selected_subunits:
        field = forms.IntegerField()
        self.fields['su%d' % (subunit['unit__id'])] = field
        self.subunit_list.append(field)

在模板中:

{% for field in form.subunit_list %}
  ...
{% endfor %}

答案 2 :(得分:1)

为了纠正gruszczy的回答,这段代码对我有用:

在表单的__init__中:

self.subunit_list = []
for subunit in self.selected_subunits:
        field = forms.IntegerField()
        self.fields['su%d' % (subunit['unit__id'])] = field
        self.subunit_list.append(self['su%d' % (subunit['unit__id'])])

在你的模板中:

{% for field in form.subunit_list %}
  <!-- show form field (inputbox) -->
  {{ field }}
{% endfor %}