我正在尝试在模板上的表单集中循环表单。我已经看到了两种不同的方法,这似乎并没有对我使用的代码产生影响。
{{ formset.management_form }}
{% for form in formset %}
{{ form }}
{% endfor %}
和...
{{ formset.management_form }}
{% for form in formset.forms %}
{{ form }}
{% endfor %}
这有什么不同吗?为什么要把.forms放在最后?
答案 0 :(得分:3)
根据BaseFormset类的来源:
def __iter__(self):
"""Yields the forms in the order they should be rendered"""
return iter(self.forms)
@cached_property
def forms(self):
"""
Instantiate forms at first property access.
"""
# DoS protection is included in total_form_count()
forms = [self._construct_form(i, **self.get_form_kwargs(i))
for i in range(self.total_form_count())]
return forms
两种方法(for form in formset
和for form in formset.forms
)都相同。
您会看到,每次__iter__
时,用于for
循环的self.forms
都会产生。另一方面,for form in formset.forms
遍历同一事物self.forms
。