[Django]-Custom validation for formset in Django

6👍

Managed to make it work, full working code below:

forms.py

class SellerResultForm(forms.ModelForm):

    class Meta:
        model = SellerResult
        fields = ('month', 'year', 'result',)
        widgets = {
            'month': forms.Select(attrs={'class': 'form-control',}),
            'year': forms.Select(attrs={'class': 'form-control',}),
            'result': forms.TextInput(attrs={'class': 'form-control',}),
        }

    def has_changed(self): #used for saving data from initial
        changed_data = super(SellerResultForm, self).has_changed()
        return bool(self.initial or changed_data)

    #no clean method here anymore

class BaseSellerResultFormSet(BaseModelFormSet):
    def clean(self):
        super(BaseSellerResultFormSet, self).clean()

        years = []
        for form in self.forms:
            year = form.cleaned_data['year']
            years.append(year)
        if years.count(2017) > 12:
            raise forms.ValidationError('You selected more than 12 months for 2017')

I have then quite struggled to get this ValidationError to render in my template, the errors are available with {{ formset.non_form_errors }} and not {{ formset.errors }} as I expected initially.

0👍

Override the clean method of the formset. self.forms will contain all of the forms.

Leave a comment