Reputation: 64699
What's the appropriate way to throw a ValidationError exception in a Django form?
There seems to be a few different mutually-exclusive ways to throw this exception. If I have a custom clean()
method in a form, and the error doesn't refer to any specific field, then I have to throw it like:
raise ValidationError({NON_FIELD_ERRORS: ["Something's wrong!"]})
However, if I do this inside a custom clean()
method of an InlineFormSet, it breaks Django's validation framework and throws the error:
AttributeError: 'ValidationError' object has no attribute 'error_list'
If I instead change my code to:
raise ValidationError("Something's wrong!")
then it works just fine and I see a nice user-friendly red validation error on my web page. However, this syntax fails almost anywhere else, and confusingly throws the error 'ValidationError' object has no attribute 'error_list'
if I don't use the raise ValidationError({...})
syntax. Why is this?
Upvotes: 6
Views: 4871
Reputation: 38922
In any class that inherits from BaseFormSet, ValidationError
s raised in the clean
instance method are not associated with any particular form.
By design, you can pass a list to ValidationError
or a string in clean
for InlineFormSet. This will ensure that self.error_list
is set. This makes sense for formset because it contains a list of forms.
raise ValidationError([{NON_FIELD_ERRORS: ["Something's wrong!"]}])
This is different for ValidationError
raised in a Form
where errors raised are associated with that form. For this reason, forms support passing dict
, str
or list
to ValidationError.
Upvotes: 7