GreyZmeem
GreyZmeem

Reputation: 650

Forms ValidationError and error code

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 ValidationError exception.

# Good
ValidationError(_('Invalid value'), code='invalid')

# Bad
ValidationError(_('Invalid value'))

I have API in my application and I'm using form to validate input data.
If form is not valid, I whant to get these error codes (not error messages).

So I looked at source code of _clean_fields method of BaseForm:
https://github.com/django/django/blob/master/django/forms/forms.py#L278

except ValidationError as e:
    self._errors[name] = self.error_class(e.messages)
    if name in self.cleaned_data:
        del self.cleaned_data[name]

As I understand this parameter (self.code) is not passed anywhere and can not be obtained after the form validation.

Can someone explain what the purpose of using this error code?

Upvotes: 25

Views: 18130

Answers (2)

Ben Davis
Ben Davis

Reputation: 13830

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"}
]}

Upvotes: 25

mariodev
mariodev

Reputation: 15604

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

Upvotes: 2

Related Questions