我试图在模板上的表单集中遍历表单。我已经看到了两种不同的方法,这似乎对我使用的代码没有什么影响。
{{ formset.management_form }}
{% for form in formset %}
{{ form }}
{% endfor %}还有..。
{{ formset.management_form }}
{% for form in formset.forms %}
{{ form }}
{% endfor %}这有什么区别吗?为什么要把.forms放在最后?
发布于 2017-04-19 18:56:28
根据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)都是相同的。
您看,用于for循环的for每次都会产生self.forms。另一方面,for form in formset.forms迭代相同的东西,self.forms。
https://stackoverflow.com/questions/43503823
复制相似问题