[Django]-Forms ValidationError and error code

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

Leave a comment