django模板标签中formset和formset.forms之间的区别

时间:2017-04-19 18:49:14

标签: django django-forms django-templates templatetags

我正在尝试在模板上的表单集中循环表单。我已经看到了两种不同的方法,这似乎并没有对我使用的代码产生影响。

{{ formset.management_form }}
    {% for form in formset %}
        {{ form }}
        {% endfor %}

和...

{{ formset.management_form }}
    {% for form in formset.forms %}
        {{ form }}
        {% endfor %}

这有什么不同吗?为什么要把.forms放在最后?

1 个答案:

答案 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 formsetfor form in formset.forms)都相同。

您会看到,每次__iter__时,用于for循环的self.forms都会产生。另一方面,for form in formset.forms遍历同一事物self.forms