2017-04-19 45 views
1

我试图通过表单在我的模板上的formset循环。我已经看到了这样做的两种不同的方式,它似乎没有影响我的代码,我使用哪一个。django模板标记中的formset和formset.forms之间的区别

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

而且......

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

这是否有什么区别?为什么要把.forms放到最后?

回答

2

按照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

+0

很好的解释谢谢:) –

相关问题