Skip to content Skip to sidebar Skip to footer

How To Properly Throw A ValidationError In Django?

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 cus

Solution 1:

In any class that inherits from BaseFormSet, ValidationErrors 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.

References


Post a Comment for "How To Properly Throw A ValidationError In Django?"