Getting a list of errors in a Django form

Question:

I’m trying to create a form in Django. That works and all, but I want all the errors to be at the top of the form, not next to each field that has the error. I tried looping over form.errors, but it only showed the name of the field that had an error, not an error message such as “Name is required.”

This is pretty much what I’d like to be able to use at the top of the form:

{% if form.??? %}
    <ul class="errorlist">
    {% for error in form.??? %}
        <li>{{ error }}</li>
    {% endfor %}
    </ul>
{% endif %}

What would I use for ??? there? It’s not errors; that just outputs the names of the fields.

Asked By: icktoofay

||

Answers:

form.errors is a dictionary. When you do {% for error in form.errors %} error corresponds to the key.

Instead try

{% for field, errors in form.errors.items %}
    {% for error in errors %}
...

Etc.

Answered By: Danny Roberts

If you want something simple with a condition take this way :

{% if form.errors %}
  <ul>
    {% for error in form.errors %} 
      <li>{{ error }}</li>
    {% endfor %}
  </ul>
{% endif %}  

If you want more info and see the name and the error of the field, do this:

{% if form.errors %}
  <ul>
    {% for key,value in form.errors.items %} 
      <li>{{ key|escape }} : {{ value|escape }}</li>
    {% endfor %}
  </ul>
{% endif %}

If you want to understant form.errors is a big dictionary.

Answered By: Buky

Dannys’s answer is not a good idea. You could get a ValueError.

{% if form.errors %}
      {% for field in form %}

           {% for error in field.errors %}
                {{field.label}}: {{ error|escape }}
           {% endfor %}

      {% endfor %}
{% endif %}
Answered By: sandes

You can use this code:

{% if form.errors %}
    {% for field in form %}
        {% for error in field.errors %}
            <div class="alert alert-danger">
                <strong>{{ error|escape }}</strong>
            </div>
        {% endfor %}
    {% endfor %}

    {% for error in form.non_field_errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
    {% endfor %}

{% endif %}

this add https://docs.djangoproject.com/en/3.0/ref/forms/api/#django.forms.Form.non_field_error

Answered By: NEFEGAGO