Thursday, 20 May 2021

Django - inline formset validation

I'm trying to validate my inline formset cost value's to make sure that it adds up to 100. The formset is returned 5 times so foreach the value should be added until 100 is hit. If it's more or less than that show an error & not allow the user to hit the create button. I'm trying to validated all the forms combined not each form value.

Models.py

class EstimatedBudgetForm(forms.ModelForm):
def clean(self):
    # get forms that actually have valid data
    count = 0
    for percentage in self.cost:
        try:
            if percentage.cleaned_data:
                count += percentage
        except AttributeError:
            # annoyingly, if a subform is invalid Django explicity raises
            # an AttributeError for cleaned_data
            pass
    if count != 100:
        raise forms.ValidationError('Percentage must equal 100%')

Views.py

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


from Django - inline formset validation

No comments:

Post a Comment