24π
β
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"}
]}
π€Ben Davis
2π
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
π€mariodev
- [Django]-Annotate with value of latest related in Django 1.8 using conditional annotation
- [Django]-In PyCharm, how to navigate to the top of the file?
- [Django]-How to include JavaScript in Django Templates?
Source:stackexchange.com