Skip to content Skip to sidebar Skip to footer

Getting A List Of Errors In A Django Form

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 f

Solution 1:

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.


Solution 2:

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 %}

Solution 3:

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.


Solution 4:

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


Post a Comment for "Getting A List Of Errors In A Django Form"