[Django]-Django – inline formset validation

5πŸ‘

βœ…

To perform validation for a formset one should override the clean method of the formset (not the form). For an inline formset you need to inherit from BaseInlineFormSet and use that (For more information see Overriding clean() on a ModelFormSet [Django docs]):

from django.forms import BaseInlineFormSet


class MyInlineFormset(BaseInlineFormSet):
    def clean(self):
        super().clean()
        count = 0
        for form in self.forms:
            if not form.errors: # No need for a try-except, just check if the form doesn't have errors
                count += form.cleaned_data['cost']
        if count != 100: # This condition might not work if you are dealing with floating point numbers
            raise forms.ValidationError('Percentage must equal 100%')

Next while making the formset, specify the formset kwarg rather than form:

EstimatedBudgetChildFormset = inlineformset_factory(
  Project, EstimatedBudget, fields=('project', 'item', 'cost', 'time'), can_delete=False, formset=MyInlineFormset, extra=5, widgets={'item': forms.Select(attrs={'disabled': True})},
)

Leave a comment