Django displays table row errors in {{form.as_table}}

I really find that quick form output keys, such as as_table, are really convenient. However, displaying errors when using these methods seems a bit controversial to me. When I use the format as_table, I would like my field errors to be displayed according to the formatting of the table. I can manually compose my forms as follows:

<table>
{% for error in form.non_field_errors %}
<tr><td>{{ error }}</td></tr>
{% endfor %}
{% endif %}

{% if form.username.errors %}
{% for error in form.username.errors %}
<tr><td>{{ error }}</td></tr>
{% endfor %}
{% endif %}
<tr><th><label for="id_username">Name:</label></th><td>{{ form.username }}</td></td>

{% if form.password.errors %}
{% for error in form.password.errors %}
<tr><td>{{ error }}</td></tr>
{% endfor %}
{% endif %}
<tr><th><label for="id_password">Password:</label>/th><td>{{ form.password }}</td></td>

But I want to know what if there is an easier way to do this? Maybe I missed something in the documents? Or maybe some other method that you use?

+5
source share
1 answer

How errors are displayed , .

reusable template, .

table_form.html:

<table>
{% for error in form.non_field_errors %}
    <tr><td>{{ error }}</td></tr>
{% endfor %}

{% for field in form %}
    {% for error in form.username.errors %}
    <tr><td>{{ error }}</td></tr>
    {% endfor %}
    <tr><th>{{ field.label_tag }}:</th><td>{{ field }}</td></td>
{% endfor %}
</table>

template.html:

<form>
    {% include 'table_form.html' %}
</form>

, . , form1 form2:

template.html:

<form>
    {% include 'table_form.html with form=form1 %}
</form>

<form>
    {% include 'table_form.html with form=form2 %}
</form>

as_table , BaseForm:

210     def as_table(self):
211         "Returns this form rendered as HTML <tr>s -- excluding the <table></table>."
212         return self._html_output(
213             normal_row = u'<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>',
214             error_row = u'<tr><td colspan="2">%s</td></tr>',
215             row_ender = u'</td></tr>',
216             help_text_html = u'<br /><span class="helptext">%s</span>',
217             errors_on_separate_row = False)

{{form.as_table}}

+10

All Articles