special field names default minimum number of forms in a formset default maximum number of forms in a formset to prevent memory exhaustion keep track of how many form instances are displayed on the page if adding new forms via javascript you should increment the count field of this form as well minnumformcount and maxnumformcount are output with the rest of the management form but only for the convenience of clientside code the post value of them returned from the client is not checked when the management form is invalid we don t know how many forms were submitted a collection of instances of the same form class yield the forms in the order they should be rendered return iterself forms def getitemself index return true since all formsets have a management form which is not included in the length return the managementform instance for this formset if self isbound form managementform self data autoidself autoid prefixself prefix rendererself renderer form fullclean else form managementform autoidself autoid prefixself prefix initial totalformcount self totalformcount initialformcount self initialformcount minnumformcount self minnum maxnumformcount self maxnum rendererself renderer return form def totalformcountself return absolutemax if it is lower than the actual total form count in the data this is dos protection to prevent clients from forcing the server to instantiate arbitrary numbers of forms allow all existing related objectsinlines to be displayed but don t allow extra beyond maxnum return the number of forms that are required in this formset if self isbound return self managementform cleaneddatainitialformcount else use the length of the initial data if it s there 0 otherwise initialforms lenself initial if self initial else 0 return initialforms cachedproperty def formsself dos protection is included in totalformcount return additional keyword arguments for each individual formset form index will be none if the form being constructed is a new empty form instantiate and return the ith form instance in a formset defaults autoid self autoid prefix self addprefixi errorclass self errorclass don t render the html required attribute as it may cause incorrect validation for extra optional and deleted forms in the formset userequiredattribute false renderer self formrenderer if self isbound defaultsdata self data defaultsfiles self files if self initial and initial not in kwargs try defaultsinitial self initiali except indexerror pass allow extra forms to be empty unless they re part of the minimum forms if i self initialformcount and i self minnum defaultsemptypermitted true defaults updatekwargs form self formdefaults self addfieldsform i return form property def initialformsself return a list of all the extra forms in this formset return self formsself initialformcount property def emptyformself formkwargs self getformkwargsnone autoid self autoid prefix self addprefixprefix emptypermitted true userequiredattribute false renderer self formrenderer form self formformkwargs self addfieldsform none return form property def cleaneddataself if not self isvalid raise attributeerror s object has no attribute cleaneddata self class name return form cleaneddata for form in self forms property def deletedformsself construct deletedformindexes which is just a list of form indexes that have had their deletion widget set to true if this is an extra form and hasn t changed don t consider it return a list of form in the order specified by the incoming data raise an attributeerror if ordering is not allowed construct ordering which is a list of formindex orderfieldvalue tuples after constructing this list we ll sort it by orderfieldvalue so we have a way to get to the form indexes in the order specified by the form data if this is an extra form and hasn t changed don t consider it don t add data marked for deletion to self ordereddata after we re done populating self ordering sort it a sort function to order things numerically ascending but none should be sorted below anything else allowing none as a comparison value makes it so we can leave ordering fields blank return a list of form cleaneddata dicts in the order specified by the form data return an errorlist of errors that aren t associated with a particular form i e from formset clean return an empty errorlist if there are none return a list of form errors for every form in self forms if self errors is none self fullclean return self errors def totalerrorcountself return whether or not the form was marked for deletion return form cleaneddata getdeletionfieldname false def isvalidself accessing errors triggers a full clean the first time only list comprehension ensures isvalid is called for all forms forms due to be deleted shouldn t cause the formset to be invalid clean all of self data and populate self errors and self nonformerrors empty forms are unchanged forms beyond those with initial data accessing errors calls fullclean if necessary shoulddeleteform requires cleaneddata give self clean a chance to do crossform validation hook for doing any extra formsetwide cleaning after form clean has been called on every form any validationerror raised by this method will not be associated with a particular form it will be accessible via formset nonformerrors return true if data in any form differs from initial return anyform haschanged for form in self def addfieldsself form index only prefill the ordering field for initial forms return true if the formset needs to be multipart i e it has fileinput or false otherwise all the forms on a formset are the same so you only need to interrogate the first form for media return a formset for the given form class if minnum is none minnum defaultminnum if maxnum is none maxnum defaultmaxnum absolutemax is a hard limit on forms instantiated to prevent memoryexhaustion attacks default to maxnum defaultmaxnum which is 2 defaultmaxnum if maxnum is none in the first place if absolutemax is none absolutemax maxnum defaultmaxnum if maxnum absolutemax raise valueerror absolutemax must be greater or equal to maxnum attrs form form extra extra canorder canorder candelete candelete candeleteextra candeleteextra minnum minnum maxnum maxnum absolutemax absolutemax validatemin validatemin validatemax validatemax renderer renderer return typeform name formset formset attrs def allvalidformsets list comprehension ensures isvalid is called for all formsets special field names default minimum number of forms in a formset default maximum number of forms in a formset to prevent memory exhaustion keep track of how many form instances are displayed on the page if adding new forms via javascript you should increment the count field of this form as well min_num_form_count and max_num_form_count are output with the rest of the management form but only for the convenience of client side code the post value of them returned from the client is not checked when the management form is invalid we don t know how many forms were submitted a collection of instances of the same form class yield the forms in the order they should be rendered return the form at the given index based on the rendering order return true since all formsets have a management form which is not included in the length return the managementform instance for this formset return the total number of forms in this formset return absolute_max if it is lower than the actual total form count in the data this is dos protection to prevent clients from forcing the server to instantiate arbitrary numbers of forms allow all existing related objects inlines to be displayed but don t allow extra beyond max_num return the number of forms that are required in this formset use the length of the initial data if it s there 0 otherwise instantiate forms at first property access dos protection is included in total_form_count return additional keyword arguments for each individual formset form index will be none if the form being constructed is a new empty form instantiate and return the i th form instance in a formset don t render the html required attribute as it may cause incorrect validation for extra optional and deleted forms in the formset allow extra forms to be empty unless they re part of the minimum forms return a list of all the initial forms in this formset return a list of all the extra forms in this formset return a list of form cleaned_data dicts for every form in self forms return a list of forms that have been marked for deletion construct _deleted_form_indexes which is just a list of form indexes that have had their deletion widget set to true if this is an extra form and hasn t changed don t consider it return a list of form in the order specified by the incoming data raise an attributeerror if ordering is not allowed construct _ordering which is a list of form_index order_field_value tuples after constructing this list we ll sort it by order_field_value so we have a way to get to the form indexes in the order specified by the form data if this is an extra form and hasn t changed don t consider it don t add data marked for deletion to self ordered_data after we re done populating self _ordering sort it a sort function to order things numerically ascending but none should be sorted below anything else allowing none as a comparison value makes it so we can leave ordering fields blank infinity larger than any number return a list of form cleaned_data dicts in the order specified by the form data return an errorlist of errors that aren t associated with a particular form i e from formset clean return an empty errorlist if there are none return a list of form errors for every form in self forms return the number of errors across all forms in the formset return whether or not the form was marked for deletion return true if every form in self forms is valid accessing errors triggers a full clean the first time only list comprehension ensures is_valid is called for all forms forms due to be deleted shouldn t cause the formset to be invalid clean all of self data and populate self _errors and self _non_form_errors stop further processing empty forms are unchanged forms beyond those with initial data accessing errors calls full_clean if necessary _should_delete_form requires cleaned_data give self clean a chance to do cross form validation hook for doing any extra formset wide cleaning after form clean has been called on every form any validationerror raised by this method will not be associated with a particular form it will be accessible via formset non_form_errors return true if data in any form differs from initial a hook for adding extra fields on to each form instance only pre fill the ordering field for initial forms return true if the formset needs to be multipart i e it has fileinput or false otherwise all the forms on a formset are the same so you only need to interrogate the first form for media return a formset for the given form class absolute_max is a hard limit on forms instantiated to prevent memory exhaustion attacks default to max_num default_max_num which is 2 default_max_num if max_num is none in the first place validate every formset and return true if all are valid list comprehension ensures is_valid is called for all formsets
from django.core.exceptions import ValidationError
from django.forms import Form
from django.forms.fields import BooleanField, IntegerField
from django.forms.renderers import get_default_renderer
from django.forms.utils import ErrorList, RenderableFormMixin
from django.forms.widgets import CheckboxInput, HiddenInput, NumberInput
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from django.utils.translation import ngettext_lazy

__all__ = ("BaseFormSet", "formset_factory", "all_valid")


TOTAL_FORM_COUNT = "TOTAL_FORMS"
INITIAL_FORM_COUNT = "INITIAL_FORMS"
MIN_NUM_FORM_COUNT = "MIN_NUM_FORMS"
MAX_NUM_FORM_COUNT = "MAX_NUM_FORMS"
ORDERING_FIELD_NAME = "ORDER"
DELETION_FIELD_NAME = "DELETE"


DEFAULT_MIN_NUM = 0


DEFAULT_MAX_NUM = 1000


class ManagementForm(Form):
    

    TOTAL_FORMS = IntegerField(widget=HiddenInput)
    INITIAL_FORMS = IntegerField(widget=HiddenInput)
    
    
    
    MIN_NUM_FORMS = IntegerField(required=False, widget=HiddenInput)
    MAX_NUM_FORMS = IntegerField(required=False, widget=HiddenInput)

    def clean(self):
        cleaned_data = super().clean()
        
        
        cleaned_data.setdefault(TOTAL_FORM_COUNT, 0)
        cleaned_data.setdefault(INITIAL_FORM_COUNT, 0)
        return cleaned_data


class BaseFormSet(RenderableFormMixin):
    

    deletion_widget = CheckboxInput
    ordering_widget = NumberInput
    default_error_messages = {
        "missing_management_form": _(
            "ManagementForm data is missing or has been tampered with. Missing fields: "
            "%(field_names)s. You may need to file a bug report if the issue persists."
        ),
        "too_many_forms": ngettext_lazy(
            "Please submit at most %(num)d form.",
            "Please submit at most %(num)d forms.",
            "num",
        ),
        "too_few_forms": ngettext_lazy(
            "Please submit at least %(num)d form.",
            "Please submit at least %(num)d forms.",
            "num",
        ),
    }

    template_name_div = "django/forms/formsets/div.html"
    template_name_p = "django/forms/formsets/p.html"
    template_name_table = "django/forms/formsets/table.html"
    template_name_ul = "django/forms/formsets/ul.html"

    def __init__(
        self,
        data=None,
        files=None,
        auto_id="id_%s",
        prefix=None,
        initial=None,
        error_class=ErrorList,
        form_kwargs=None,
        error_messages=None,
    ):
        self.is_bound = data is not None or files is not None
        self.prefix = prefix or self.get_default_prefix()
        self.auto_id = auto_id
        self.data = data or {}
        self.files = files or {}
        self.initial = initial
        self.form_kwargs = form_kwargs or {}
        self.error_class = error_class
        self._errors = None
        self._non_form_errors = None
        self.form_renderer = self.renderer
        self.renderer = self.renderer or get_default_renderer()

        messages = {}
        for cls in reversed(type(self).__mro__):
            messages.update(getattr(cls, "default_error_messages", {}))
        if error_messages is not None:
            messages.update(error_messages)
        self.error_messages = messages

    def __iter__(self):
        
        return iter(self.forms)

    def __getitem__(self, index):
        
        return self.forms[index]

    def __len__(self):
        return len(self.forms)

    def __bool__(self):
        
        return True

    def __repr__(self):
        if self._errors is None:
            is_valid = "Unknown"
        else:
            is_valid = (
                self.is_bound
                and not self._non_form_errors
                and not any(form_errors for form_errors in self._errors)
            )
        return "<%s: bound=%s valid=%s total_forms=%s>" % (
            self.__class__.__qualname__,
            self.is_bound,
            is_valid,
            self.total_form_count(),
        )

    @cached_property
    def management_form(self):
        
        if self.is_bound:
            form = ManagementForm(
                self.data,
                auto_id=self.auto_id,
                prefix=self.prefix,
                renderer=self.renderer,
            )
            form.full_clean()
        else:
            form = ManagementForm(
                auto_id=self.auto_id,
                prefix=self.prefix,
                initial={
                    TOTAL_FORM_COUNT: self.total_form_count(),
                    INITIAL_FORM_COUNT: self.initial_form_count(),
                    MIN_NUM_FORM_COUNT: self.min_num,
                    MAX_NUM_FORM_COUNT: self.max_num,
                },
                renderer=self.renderer,
            )
        return form

    def total_form_count(self):
        
        if self.is_bound:
            
            
            
            
            return min(
                self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max
            )
        else:
            initial_forms = self.initial_form_count()
            total_forms = max(initial_forms, self.min_num) + self.extra
            
            
            if initial_forms > self.max_num >= 0:
                total_forms = initial_forms
            elif total_forms > self.max_num >= 0:
                total_forms = self.max_num
        return total_forms

    def initial_form_count(self):
        
        if self.is_bound:
            return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
        else:
            
            initial_forms = len(self.initial) if self.initial else 0
        return initial_forms

    @cached_property
    def forms(self):
        
        
        return [
            self._construct_form(i, **self.get_form_kwargs(i))
            for i in range(self.total_form_count())
        ]

    def get_form_kwargs(self, index):
        
        return self.form_kwargs.copy()

    def _construct_form(self, i, **kwargs):
        
        defaults = {
            "auto_id": self.auto_id,
            "prefix": self.add_prefix(i),
            "error_class": self.error_class,
            
            
            
            "use_required_attribute": False,
            "renderer": self.form_renderer,
        }
        if self.is_bound:
            defaults["data"] = self.data
            defaults["files"] = self.files
        if self.initial and "initial" not in kwargs:
            try:
                defaults["initial"] = self.initial[i]
            except IndexError:
                pass
        
        
        if i >= self.initial_form_count() and i >= self.min_num:
            defaults["empty_permitted"] = True
        defaults.update(kwargs)
        form = self.form(**defaults)
        self.add_fields(form, i)
        return form

    @property
    def initial_forms(self):
        
        return self.forms[: self.initial_form_count()]

    @property
    def extra_forms(self):
        
        return self.forms[self.initial_form_count() :]

    @property
    def empty_form(self):
        form_kwargs = {
            **self.get_form_kwargs(None),
            "auto_id": self.auto_id,
            "prefix": self.add_prefix("__prefix__"),
            "empty_permitted": True,
            "use_required_attribute": False,
            "renderer": self.form_renderer,
        }
        form = self.form(**form_kwargs)
        self.add_fields(form, None)
        return form

    @property
    def cleaned_data(self):
        
        if not self.is_valid():
            raise AttributeError(
                "'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__
            )
        return [form.cleaned_data for form in self.forms]

    @property
    def deleted_forms(self):
        
        if not self.is_valid() or not self.can_delete:
            return []
        
        
        if not hasattr(self, "_deleted_form_indexes"):
            self._deleted_form_indexes = []
            for i, form in enumerate(self.forms):
                
                if i >= self.initial_form_count() and not form.has_changed():
                    continue
                if self._should_delete_form(form):
                    self._deleted_form_indexes.append(i)
        return [self.forms[i] for i in self._deleted_form_indexes]

    @property
    def ordered_forms(self):
        
        if not self.is_valid() or not self.can_order:
            raise AttributeError(
                "'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__
            )
        
        
        
        
        if not hasattr(self, "_ordering"):
            self._ordering = []
            for i, form in enumerate(self.forms):
                
                if i >= self.initial_form_count() and not form.has_changed():
                    continue
                
                if self.can_delete and self._should_delete_form(form):
                    continue
                self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME]))
            
            
            
            
            

            def compare_ordering_key(k):
                if k[1] is None:
                    return (1, 0)  
                return (0, k[1])

            self._ordering.sort(key=compare_ordering_key)
        
        
        return [self.forms[i[0]] for i in self._ordering]

    @classmethod
    def get_default_prefix(cls):
        return "form"

    @classmethod
    def get_deletion_widget(cls):
        return cls.deletion_widget

    @classmethod
    def get_ordering_widget(cls):
        return cls.ordering_widget

    def non_form_errors(self):
        
        if self._non_form_errors is None:
            self.full_clean()
        return self._non_form_errors

    @property
    def errors(self):
        
        if self._errors is None:
            self.full_clean()
        return self._errors

    def total_error_count(self):
        
        return len(self.non_form_errors()) + sum(
            len(form_errors) for form_errors in self.errors
        )

    def _should_delete_form(self, form):
        
        return form.cleaned_data.get(DELETION_FIELD_NAME, False)

    def is_valid(self):
        
        if not self.is_bound:
            return False
        
        self.errors
        
        
        forms_valid = all(
            [
                form.is_valid()
                for form in self.forms
                if not (self.can_delete and self._should_delete_form(form))
            ]
        )
        return forms_valid and not self.non_form_errors()

    def full_clean(self):
        
        self._errors = []
        self._non_form_errors = self.error_class(
            error_class="nonform", renderer=self.renderer
        )
        empty_forms_count = 0

        if not self.is_bound:  
            return

        if not self.management_form.is_valid():
            error = ValidationError(
                self.error_messages["missing_management_form"],
                params={
                    "field_names": ", ".join(
                        self.management_form.add_prefix(field_name)
                        for field_name in self.management_form.errors
                    ),
                },
                code="missing_management_form",
            )
            self._non_form_errors.append(error)

        for i, form in enumerate(self.forms):
            
            if not form.has_changed() and i >= self.initial_form_count():
                empty_forms_count += 1
            
            
            form_errors = form.errors
            if self.can_delete and self._should_delete_form(form):
                continue
            self._errors.append(form_errors)
        try:
            if (
                self.validate_max
                and self.total_form_count() - len(self.deleted_forms) > self.max_num
            ) or self.management_form.cleaned_data[
                TOTAL_FORM_COUNT
            ] > self.absolute_max:
                raise ValidationError(
                    self.error_messages["too_many_forms"] % {"num": self.max_num},
                    code="too_many_forms",
                )
            if (
                self.validate_min
                and self.total_form_count()
                - len(self.deleted_forms)
                - empty_forms_count
                < self.min_num
            ):
                raise ValidationError(
                    self.error_messages["too_few_forms"] % {"num": self.min_num},
                    code="too_few_forms",
                )
            
            self.clean()
        except ValidationError as e:
            self._non_form_errors = self.error_class(
                e.error_list,
                error_class="nonform",
                renderer=self.renderer,
            )

    def clean(self):
        
        pass

    def has_changed(self):
        
        return any(form.has_changed() for form in self)

    def add_fields(self, form, index):
        
        initial_form_count = self.initial_form_count()
        if self.can_order:
            
            if index is not None and index < initial_form_count:
                form.fields[ORDERING_FIELD_NAME] = IntegerField(
                    label=_("Order"),
                    initial=index + 1,
                    required=False,
                    widget=self.get_ordering_widget(),
                )
            else:
                form.fields[ORDERING_FIELD_NAME] = IntegerField(
                    label=_("Order"),
                    required=False,
                    widget=self.get_ordering_widget(),
                )
        if self.can_delete and (
            self.can_delete_extra or (index is not None and index < initial_form_count)
        ):
            form.fields[DELETION_FIELD_NAME] = BooleanField(
                label=_("Delete"),
                required=False,
                widget=self.get_deletion_widget(),
            )

    def add_prefix(self, index):
        return "%s-%s" % (self.prefix, index)

    def is_multipart(self):
        
        if self.forms:
            return self.forms[0].is_multipart()
        else:
            return self.empty_form.is_multipart()

    @property
    def media(self):
        
        
        if self.forms:
            return self.forms[0].media
        else:
            return self.empty_form.media

    @property
    def template_name(self):
        return self.renderer.formset_template_name

    def get_context(self):
        return {"formset": self}


def formset_factory(
    form,
    formset=BaseFormSet,
    extra=1,
    can_order=False,
    can_delete=False,
    max_num=None,
    validate_max=False,
    min_num=None,
    validate_min=False,
    absolute_max=None,
    can_delete_extra=True,
    renderer=None,
):
    
    if min_num is None:
        min_num = DEFAULT_MIN_NUM
    if max_num is None:
        max_num = DEFAULT_MAX_NUM
    
    
    
    if absolute_max is None:
        absolute_max = max_num + DEFAULT_MAX_NUM
    if max_num > absolute_max:
        raise ValueError("'absolute_max' must be greater or equal to 'max_num'.")
    attrs = {
        "form": form,
        "extra": extra,
        "can_order": can_order,
        "can_delete": can_delete,
        "can_delete_extra": can_delete_extra,
        "min_num": min_num,
        "max_num": max_num,
        "absolute_max": absolute_max,
        "validate_min": validate_min,
        "validate_max": validate_max,
        "renderer": renderer,
    }
    return type(form.__name__ + "FormSet", (formset,), attrs)


def all_valid(formsets):
    
    
    return all([formset.is_valid() for formset in formsets])