如何渲染 Django 表单错误而不是在 UL 中?
我的 Django 表单中的错误按照 docs 在 UL 中呈现...
Django
{{ form.non_field_errors }}
HTML
<ul class="errorlist">
<li>Sender is required.</li>
</ul>
如何我可以呈现错误,使它们不出现在 UL 中,而是出现在每个字段相关错误的段落标记中吗?所以理想情况下...
<ul>
<li>
<label>...</label>
<input>...</input>
<p>Error message...</p>
</li>
</ul>
编辑:
为了清楚起见,我应该在我的示例中使用此代码...
{{ form.fieldname.errors }}
The errors in my Django form are rendering in a UL as per the docs...
Django
{{ form.non_field_errors }}
HTML
<ul class="errorlist">
<li>Sender is required.</li>
</ul>
How can I render the errors so they appear not in a UL, but in a paragraph tag for each fields relevant error? So ideally...
<ul>
<li>
<label>...</label>
<input>...</input>
<p>Error message...</p>
</li>
</ul>
EDIT:
I should have used this code in my example for clarity...
{{ form.fieldname.errors }}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在模板中显示错误,如下所示:
You can display your error as the following in your template:
它显然无法在字段的上下文中呈现,因为正如属性名称所暗示的那样,这些是“非字段错误”。解决此问题的唯一方法是在验证时在正确的位置添加错误。例如,执行以下操作会导致非字段错误:
但是,您可以执行以下操作以使该错误仍然显示在右侧字段上:
更新:
来自 Django 文档:
It obviously can't render within the context of the field because these are "non-field errors" as the attribute name implies. The only way to fix this is to add the error in the right place when validating. For example, doing the following results in non-field errors:
However, you can do the following to make that error still show on the right field:
UPDATE:
From the Django docs: