【问题标题】:Difference between formset and formset.forms in django template tagsdjango模板标签中formset和formset.forms的区别
【发布时间】:2017-04-19 18:49:13
【问题描述】:

我正在尝试在我的模板的表单集中循环浏览表单。而且我已经看到了两种不同的方法,我使用哪一种似乎对我的代码没有影响。

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

还有……

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

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

【问题讨论】:

    标签: django django-forms django-templates templatetags


    【解决方案1】:

    根据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)是相同的。

    您会看到,用于for 循环的__iter__ 每次都会产生self.forms。另一方面,for form in formset.forms 迭代相同的东西,self.forms

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 2014-08-08
      • 2012-10-31
      • 2011-08-22
      • 1970-01-01
      • 2018-06-11
      • 2014-07-25
      相关资源
      最近更新 更多