django 模板标签中 formset 和 formset.forms 的区别
Difference between formset and formset.forms in django template tags
我正在尝试在我的模板上的表单集中遍历表单。而且我已经看到了两种不同的方法来执行此操作,而且我使用哪种方法似乎对我的代码没有影响。
{{ formset.management_form }}
{% for form in formset %}
{{ form }}
{% endfor %}
还有...
{{ formset.management_form }}
{% for form in formset.forms %}
{{ form }}
{% endfor %}
这有什么区别吗?为什么要把 .forms 放在最后?
根据 BaseFormset class 的来源:
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
循环的 __iter__
每次 self.forms
都会产生。另一方面,for form in formset.forms
迭代相同的东西,即 self.forms
.
我正在尝试在我的模板上的表单集中遍历表单。而且我已经看到了两种不同的方法来执行此操作,而且我使用哪种方法似乎对我的代码没有影响。
{{ formset.management_form }}
{% for form in formset %}
{{ form }}
{% endfor %}
还有...
{{ formset.management_form }}
{% for form in formset.forms %}
{{ form }}
{% endfor %}
这有什么区别吗?为什么要把 .forms 放在最后?
根据 BaseFormset class 的来源:
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
循环的 __iter__
每次 self.forms
都会产生。另一方面,for form in formset.forms
迭代相同的东西,即 self.forms
.