17

At my template, I want to iterate through all form errors, including the ones that are NOT belonging to a specific field. ( which means for form.errors, it should also display for __all__ errors aswell)

I have tried several versions, Ie:

 <div id="msg">
  {% if form.errors %}
  <div class="error">
   <p><span>ERROR</span></p>
   <ul>
   {% for key,value in form.errors %}
    {% for error in value %}
     <li>{{ error }}</li>
    {% endfor %}
   {% endfor %}
   </ul>
  </div>
  {% endif %}
 </div>

Still no achievement, I will be greatful for any suggestion.

Hellnar
  • 57,479
  • 74
  • 196
  • 273

2 Answers2

39

Form errors in Django are implemented as an ErrorDict instance (which is just a subclass of dict with extras). Try a slight adjustment to your template for loop syntax:

{% for key, value in form.errors.items %}
Jarret Hardie
  • 90,470
  • 10
  • 128
  • 124
19

Are you, by any chance, looking for form.non_field_errors? That is how you would get access to the errors that aren't associated with a particular field.

{% if form.non_field_errors %}
<ul>
    {{ form.non_field_errors.as_ul }}
</ul>
{% endif %}

Check the forms.py test suite as well for another example. Search for form.non_field_errors

Nick Presta
  • 27,478
  • 6
  • 54
  • 75