1

In a django template I'd like to show all form errors on top of the form, the easiest way is by doing so:

{{ form.errors }}

The problem is that this also shows the form.non_field_errors, these are the entries contained in form.errors['__all__'].

I want to show these special errors separately, so I've tried to loop over the dict and check if the key existed:

{% for err in form.errors %}
  {% if not err.__all__ %}
    {# print error #}
  {% endif %}
{% endfor %}

but apparently this is not possible because in the template we cannot access dictionary keys starting with underscore (doc).

Question: is there a built-in way to access (and possibly print) the standard field errors and separately the non_field_errors?

Solution This was built on top of Daniel Roseman's answer:

{% if form.errors %}
    <div class="ui error icon message">
        <ul>
            {% if form.non_field_errors %}
                {% for error in form.non_field_errors %}
                    <li>{{ error|escape }}</li>
                {% endfor %}
            {% endif %}

            {% for field in form %}
                {% if field.errors %}
                    <li> {{ field.name }}
                        <ul>
                            {% for error in field.errors %}
                                <li>{{ error|escape }}</li>
                            {% endfor %}
                        </ul>
                    </li>
                {% endif %}
            {% endfor %}
        </ul>
    </div>
{% endif %}

1 Answer 1

3

You can loop over the fields and access their errors:

{% for field in form %}
    {% field.errors %}
{% endfor %}
Sign up to request clarification or add additional context in comments.

1 Comment

It should be {{ field.errors }} instead of {% field.errors %} . :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.