简体   繁体   中英

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 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?

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.

References

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM