Django form errors. get error without any html tags

I would like to receive form errors in my non-html version on my template.

by default, the error ends with <ul class="errorlist"> , which I want to avoid.

In any case, to do this without mass code changes?

+6
source share
4 answers

This section of the forms documentation section has all the details, namely this fragment:

 {% if form.subject.errors %} <ol> {% for error in form.subject.errors %} <li><strong>{{ error|escape }}</strong></li> {% endfor %} </ol> {% endif %} 

Replace form with what you call your form class in the template. In this example, subject is a field in the form. If you want to have a separate section to summarize all the errors, simply swipe the fields along them:

 {% if form.errors %} {% for field in form %} {% for error in field.errors %} {{ error|escape }} {% endfor %} {% endfor %} {% endif %} 
+6
source

There are two new methods in Django 1.7 that would also be useful to solve this problem:

Form.errors.as_data ()

 >>> f.errors.as_data() {'sender': [ValidationError(['Enter a valid email address.'])], 'subject': [ValidationError(['This field is required.'])]} 

Form.errors.as_json ()

 >>> f.errors.as_json() {"sender": [{"message": "Enter a valid email address.", "code": "invalid"}], "subject": [{"message": "This field is required.", "code": "required"}]} 
+15
source

To access errors for a specific field, use form.field_name.errors , where "field_name" is the name of the field that generates the error.

It is still useful to use a for loop if more than one error has been generated in a field.

Example:

 {% for error in form.email.errors %} <label>{{ error|escape }} </label> {% endfor %} <br> <label>Email: </label>{{ form.email }} 

Some errors may not be related specifically to a specific field, for example, an error that occurs when two password fields coincide. They must be available:

 {{ form.non_field_errors }} 
+1
source

Updated for Django 2.1

We have 4 options for accessing form errors in views.

  1. 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.

  1. 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.

  1. 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.

  1. 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 ().

0
source

Source: https://habr.com/ru/post/945600/


All Articles