[Answered ]-Django and formsets

2👍

form in self results in a call to the special method self.__iter__(), which is how iterable classes are implemented in python.

object.__iter__(self)

This method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. For mappings, it should iterate over the keys of the container.

For django’s formsets, this is the relevant code.

class BaseFormSet(object):
    """
    A collection of instances of the same Form 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

link to full source

Leave a comment