tags:

views:

416

answers:

3

When I display a form with errors using {{ f.as_p }} , the errorlist ul always comes first then the label and input field. For example:

<ul class="errorlist">
<li>This field is required.</li>
</ul>
<p>
<label for="id_content">Content:</label>
<textarea id="id_content" class="required error" name="content" cols="80" rows="10"/>
</p>

I know you can use

{% for field in f %}
<p>{{ field.label_tag }}: {{ field }}</p>
{{ field.errors }}
{% endfor %}

To change the errorlist ul position after label and field, but I want directly use f.as_p, f.as_table or {{ f }}, because it's simple and easy, especially when I have to show a lot of forms.

So the question is: Is there a way to make the errorlist ul shows after the field part by default?

+1  A: 

Form.as_p() is just a method in the Form class. Just create a new class that inherits from Form and copy-paste the as_p method and change it to your liking. Then anytime you make a new form inherit from your form class instead of Django's.

Jason Christa
thanks, I guess this is what am going to do
+2  A: 

An alternative way that will considerably ease this effort is subclassing Form (and ModelForm) in such a way that a new method is implemented to render output via an html template. How to do this is described here.

shanyu
thank you very much, this is a very good example
you are welcome.
shanyu
A: 

The loop I always use, which is fairly generic but very customizable is this:

{% for field in form %}
<tr>
    <td>{{ field.label_tag }}:</td>
    <td>
        {{ field.errors }}
        {{ field }}
        {% if field.help_text %}
        <img class="tooltip" title="{{ field.help_text }}" src="{{ MEDIA_URL }}images/icon_help.png">
        {% endif %}
    </td>
</tr>
{% endfor %}

Between table tags ofc :)

GerardJP