Search code examples
djangoerror-handlingdjango-formsinline-formset

Inserting Errors into an InlineFormSet Custom Validator


I am using the following custom form validator to ensure that there is not more than one correct entry submitted to my application through an InlineFormSet.

class BaseAnswerFormSet(forms.models.BaseInlineFormSet):
    def clean(self):
        if any(self.errors):
            return
        if len([d['correct'] for d in self.forms if d['correct'].value()]) !=1:
            raise forms.ValidationError("There must be one and only one correct answer")
        return

This is working, as the form object that is presented will return False when evaluated as .is_clean() but there is no error returned. Here is what it shows up as when I use pdb in the view that handles the POST:

(Pdb) answerformset.is_valid()
False
(Pdb) answerformset.errors
[{}, {}, {}]

Shouldn't the raise forms.ValidationError("There must be one... create an error entry? I know that each of the empty dicts in the answerformset.errors list is for each of the answer forms, but I thought that there would be a non_field_error or something like that?

How can I get this clean function to return an error that I can display in a template? How can I add a non_field_error to this?


Solution

  • Please read Custom Formset Validation. Formset custom errors can be accessed using non_form_errors:

    answerformset.non_form_errors()