Reputation: 4228
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 %}
Upvotes: 1
Views: 1692
Reputation: 599628
You can loop over the fields and access their errors:
{% for field in form %}
{% field.errors %}
{% endfor %}
Upvotes: 3