问题描述
我正在尝试在 Django 中创建一个表单.这一切都有效,但我希望所有错误都位于表单的顶部,而不是在每个有错误的字段旁边.我尝试遍历 form.errors,但它只显示有错误的字段的名称,而不是诸如需要名称"之类的错误消息.
I'm trying to create a form in Django. That works and all, but I want all the errors to be at the top of the form, not next to each field that has the error. I tried looping over form.errors, but it only showed the name of the field that had an error, not an error message such as "Name is required."
这几乎是我希望能够在表单顶部使用的内容:
This is pretty much what I'd like to be able to use at the top of the form:
{% if form.??? %}
<ul class="errorlist">
{% for error in form.??? %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
???
有什么用?这不是错误
;只输出字段的名称.
What would I use for ???
there? It's not errors
; that just outputs the names of the fields.
推荐答案
form.errors 是一本字典.当你做 {% for error in form.errors %}
错误对应的键.
form.errors is a dictionary. When you do {% for error in form.errors %}
error corresponds to the key.
不如试试
{% for field, errors in form.errors.items %}
{% for error in errors %}
...
等
这篇关于获取 Django 表单中的错误列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!