Django form errorlist render position

廉价感情. 提交于 2020-01-22 12:33:47

问题


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:


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 :)




回答2:


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.




回答3:


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.




回答4:


I use jquery appendTo to move all errorlist ul elements after the django fields element. It doesn't need any work to render the html but adjust the django default html by jquery to fix your need.

$(document).ready(function() {
    $("ul.errorlist").each(function(index){
        $(this).appendTo($(this).parent());
    });
});


来源:https://stackoverflow.com/questions/1218866/django-form-errorlist-render-position

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!