In Django documentation https://docs.djangoproject.com/en/dev/ref/forms/validation/#raising-validationerror said that it is good practice to prodive error code while raising
In Django 1.7, you can now access the original error data from the form. You can call the as_data()
method on an ErrorList
or ErrorDict
. For example: my_form.errors.as_data()
. This basically gives you the original ValidationError
object instead of the message itself. From this you can access the .code
property, eg: my_form.errors["__all__"].as_data()[0].code
.
You can also serialize form errors, great for APIs:
>>> print(form.errors.as_json())
{"__all__": [
{"message": "Your account has not been activated.", "code": "inactive"}
]}
Take a look at ValidationError definition in django src, it's used as a convenient way to pass additional identifier (similar to e.errno
in standard python exception), you can use it like this:
try:
...
raise ValidationError(u'Oops', code=0x800)
...
except ValidationError as e:
print "Error code: ", e.code