Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, loop over all form errors

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.

like image 294
Hellnar Avatar asked Mar 17 '10 13:03

Hellnar


2 Answers

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 %}
like image 177
Jarret Hardie Avatar answered Sep 29 '22 23:09

Jarret Hardie


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

like image 32
Nick Presta Avatar answered Sep 29 '22 22:09

Nick Presta