Django将表单错误输出到{{form.as_table}}中的表格行 [英] Django output form errors as table rows in {{ form.as_table }}
问题描述
我真的很容易找到表单输出快捷方式,如 as_table
。但是,在使用这些方法时显示错误似乎有点违反直觉。当我使用 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?
推荐答案
如何显示错误
/ a>和 自定义错误列表格式 显示默认错误字段输出是什么以及如何自定义。
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_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:
template.html:
<form>
{% include 'table_form.html' %}
</form>
多个表单也工作,例如查看与上下文包括form1和form2:
multiple forms work too, e.g. view with context including form1 and form2:
template.html:
template.html:
<form>
{% include 'table_form.html with form=form1 %}
</form>
<form>
{% include 'table_form.html with form=form2 %}
</form>
编辑:
以下是 as_table
在BaseForm类中定义的方法:
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)
您使用此形式的方法将允许您在使用{{form.as_table}}
overriding this method in your form will allow you to change the rendering when you use {{ form.as_table }}
这篇关于Django将表单错误输出到{{form.as_table}}中的表格行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!