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?
Django's form (and model) fields support use of utility functions and classes known as validators. A validator is a callable object or function that takes a value and returns nothing if the value is valid or raises a ValidationError if not.
Validations errors are errors when users do not respond to mandatory questions. A validation error occurs when you have validation/response checking turned on for one of the questions and the respondent fails to answer the question correctly (for numeric formatting , required response).
In most cases Eloqua's APIs will respond to requests with the standard HTTP status code definitions. If the API fails to validate a request, it will respond with a validation error message (JSON or XML) describing the issue. 400: "There was a parsing error."
In django 1.2, model validation has been added. You can now add a "clean" method to your models which raise ValidationError exceptions, and it will be called automatically when using the django admin. The clean() method is called when using the django admin, but NOT called on save() .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With