[Answer]-How to handle form.non_field_errors and form.errors?

1👍

Your if condition {% if form.errors %} is triggered when there are form errors, including non field errors.

Maybe you can convert the second block to a for loop and place the if condition within:

{% for field in form %}
    {% if field.errors %}
        <div class="alert alert-info" role="alert">
             {{ field.errors }}
        </div>
    {% endif %}
    {{ field }}
{% endfor %}

This is just a very simple example. You can extend and adapt it according to your needs.

EDIT:

even better solution would be to use django-crispy-forms:

http://django-crispy-forms.readthedocs.org/en/latest/

Don’t reinvent the wheel!

EDIT: answer the first comment below

If you really want to display all field errors in a single DIV, for whatever reason you might need that, you could eventually write:

{% if form.errors %}
    {# first block #}
    {% if form.non_field_errors %}
        {# your logic #}
    {% endif %}
    {# second block #}
    <div class="alert alert-info" role="alert">
        {% for field in form %}
            {{ field.errors }}
            {# your logic #}
        {% endfor %}
    </div>
{% endif %}

So if there are only field errors, the non field errors block won’t show up.

👤cezar

Leave a comment