Updated for Django 2.1
We have 4 options for accessing form errors in views.
- Form.errors
Access the error attribute to get a dictionary of error messages:
f.errors {'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}
In this dictionary, keys are field names, and values ββare lists of strings representing error messages. Error messages are stored in lists because there can be several error messages in a field.
You can access errors without first calling is_valid (). Form data will be checked upon the first call to is_valid () or upon access to errors.
Validation procedures will be called only once, no matter how many times you access errors or call is_valid (). This means that if the check has side effects, these side effects will be triggered only once.
- Form.errors.as_data ()
Returns a dict that maps the fields to their original ValidationError instances.
f.errors.as_data() {'sender': [ValidationError(['Enter a valid email address.'])], 'subject': [ValidationError(['This field is required.'])]}
Use this method anytime you need to identify an error by its code. This allows things such as overwriting the error message or writing custom logic in the view when the error is present. It can also be used to serialize errors in an arbitrary format (for example, XML); for example, as_json () relies on as_data ().
The need for the as_data () method is due to backward compatibility. Previously, ValidationError instances were lost as soon as their processed error messages were added to the Form.errors dictionary. Ideally, Form.errors stores ValidationError instances and methods with the as_ prefix that can display them, but it had to be done the other way around so as not to break the code that waits for visualized error messages in Form.errors.
- Form.errors.as_json (escape_html = False)
Returns errors serialized as JSON.
f.errors.as_json() {"sender": [{"message": "Enter a valid email address.", "code": "invalid"}], "subject": [{"message": "This field is required.", "code": "required"}]}
By default, as_json () does not escape its output. If you use it for something like AJAX requests to submit a form where the client interprets the response and inserts errors into the page, you should definitely avoid client-side results to avoid cross-site interaction. script attack. This is trivial using a JavaScript library such as jQuery - just use $ (el) .text (errorText) instead of .html ().
If for some reason you do not want to use client-side escaping, you can also set escape_html = True and the error messages will be escaped so you can use them directly in HTML.
- Form.errors.get_json_data (escape_html = False) [new in django 2.0]
f.errors.get_json_data(escape_html=False)
Returns errors in the form of a dictionary suitable for serialization in JSON. Form.errors.as_json () returns serialized JSON, while it returns error data before they are serialized.
The escape_html parameter behaves as described in Form.errors.as_json ().