I'm trying to loop through forms in a formset on my template. And I have seen two different ways of doing this and it doesn't seem to make a difference to my code which one I use.
{{ formset.management_form }}
{% for form in formset %}
{{ form }}
{% endfor %}
And...
{{ formset.management_form }}
{% for form in formset.forms %}
{{ form }}
{% endfor %}
Does this make any difference? Why put .forms on the end?
According to the source of the 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
Both methods (for form in formset and for form in formset.forms) are identical.
You see, the __iter__ which is used for the for loop yields each time the self.forms. On the other hand, the for form in formset.forms iterates over the same thing, the self.forms.