25

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?

2
  • Seems like that's a new addition - see the note that says "new in 1.6", which isn't even released yet - so probably it's not fully implemented everywhere. Commented Sep 13, 2013 at 9:56
  • This field also present in 1.5. Looks like you're right and it's something to be used in a future release. Commented Sep 13, 2013 at 10:06

2 Answers 2

25

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"}
]}
Sign up to request clarification or add additional context in comments.

1 Comment

As of django 1.10 the right way to access the code would be form.errors.as_data()['field_name'][0].code
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

2 Comments

Thanks for the answer! So if I want to keep the value of this code after form validation I need to rewrite _clean_fileds method?
that or see Daniel's comment above, they probably still working on that, so it's better to just wait, so you won't have incompatibilities when upgrading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.