Question

I have django template in which i am getting the form errors in to the attribute errors as html

form.html

             {% if form.errors %}  
                 <div class="span12">
                    {{form.errors}}     
                 </div>
             {% endif %}

The output of the above template code is like

html

<ul class="errorlist">
      <li>price
         <ul class="errorlist">
            <li>price is required</li></ul>
      </li>
      <li>name
         <ul class="errorlist">
            <li>name is required</li>
         </ul>
       </li>
      <li>description
         <ul class="errorlist">
            <li>description is required</li>
         </ul>
      </li>

design

price
    price is required
name
    name is required
description
    description is required

But i want to display in the format like below output

             {% if form.errors %}  
                 <div class="span12">
                    {% for error in form.errors %}
                        {{key}} : {{value}}
                    {% endfor %}
                 </div>
             {% endif %}

Required/needed output

price  : price is required
name   : name is required 
description : description is required

Can anyone please let me know how to access/use form.errors attribute in order to print/display the results in the above format ?

Edit

Or else we can send the dictionary of the errors from the view like below

def render_view(request):
   form  = Form()
   if form.is_valid():
      .....
      .....
   render_to_response('template.html',{'errors':dict(form.errors)})

In template.html

{% if errors %}
   {% for key in errors %} 
       {{key}} : {{errors.key}}
   {% endfor %} 
{% endif %}

{% endif %}

But in this case value of the key in the dictionary is not displaying so how to access it ?

Was it helpful?

Solution

as I remember form.errors is dict like object so You can try iterate over it.

{% if errors %}
   {% for key, error_list in errors.iteritems %} 
       {{key}} : {{error_list}}
   {% endfor %} 
{% endif %}

If You would Iterate this way

{% if errors %}
   {% for key in errors %} 
       {{key}} : {{errors}}
   {% endfor %} 
{% endif %}

You would iterate over dictionary keys so consider to use either items or iteritems

OTHER TIPS

Not very elegant but can try this:

{% for field in form %}
    {% if field.errors %}
        {{field.label}} : {{field.errors}}
    {% endif %}
{% endfor %}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top