Django output form errors as table rows in {{ form.as_table }}
I really find the form output shortcuts such as as_table
really handy. However, displaying errors while using those methods seems a little counterintuitive to me. When I use the as_table
format, I would like my field specific errors to be displayed in accordance to table formatting. I can manually piece my forms together like so:
<开发者_如何学编程;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 what I want to know is that if there a simpler way to do this? Maybe something I missed in the docs? Or perhaps a different method any of you employ?
How errors are displayed
and customizing the error list format show what the default error field output is and how to customize it.
I have been using a reusable template
in my projects recently, which has been working well for me.
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>
multiple forms work too, e.g. view with context including form1 and form2:
template.html:
<form>
{% include 'table_form.html with form=form1 %}
</form>
<form>
{% include 'table_form.html with form=form2 %}
</form>
edit:
Here is the as_table
method as defined in the BaseForm class:
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)
overriding this method in your form will allow you to change the rendering when you use {{ form.as_table }}
精彩评论