获取Django表单中的错误列表

时间:2021-05-22 19:17:22

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."

我正在尝试在Django中创建一个表单。这是有效的,但我希望所有错误都在表单的顶部,而不是在每个有错误的字段旁边。我尝试循环form.errors,但它只显示有错误的字段的名称,而不是错误消息,如“名称是必需的”。

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.

我会用什么???那里?这不是错误;只输出字段的名称。

2 个解决方案

#1


48  

form.errors is a dictionary. When you do {% for error in form.errors %} error corresponds to the key.

form.errors是一本字典。当你执行{%for form in form.errors%}时,错误对应于密钥。

Instead try

相反,试试

{% for field, errors in form.errors.items %}
    {% for error in errors %}
...

Etc.

等等。

#2


2  

If you want something simple with a condition take this way :

如果你想要一个简单的条件采取这种方式:

{% if form.errors %}
  <ul>
    {% for error in form.errors %} 
      <li>{{ error }}</li>
    {% endfor %}
  </ul>
{% endif %}  

If you want more info and see the name and the error of the field, do this:

如果您想要更多信息并查看字段的名称和错误,请执行以下操作:

{% if form.errors %}
  <ul>
    {% for key,value in form.errors.items %} 
      <li>{{ key|escape }} : {{ value|escape }}</li>
    {% endfor %}
  </ul>
{% endif %}

If you want to understant form.errors is a big dictionary.

如果你想理解form.errors是一本很大的字典。

#1


48  

form.errors is a dictionary. When you do {% for error in form.errors %} error corresponds to the key.

form.errors是一本字典。当你执行{%for form in form.errors%}时,错误对应于密钥。

Instead try

相反,试试

{% for field, errors in form.errors.items %}
    {% for error in errors %}
...

Etc.

等等。

#2


2  

If you want something simple with a condition take this way :

如果你想要一个简单的条件采取这种方式:

{% if form.errors %}
  <ul>
    {% for error in form.errors %} 
      <li>{{ error }}</li>
    {% endfor %}
  </ul>
{% endif %}  

If you want more info and see the name and the error of the field, do this:

如果您想要更多信息并查看字段的名称和错误,请执行以下操作:

{% if form.errors %}
  <ul>
    {% for key,value in form.errors.items %} 
      <li>{{ key|escape }} : {{ value|escape }}</li>
    {% endfor %}
  </ul>
{% endif %}

If you want to understant form.errors is a big dictionary.

如果你想理解form.errors是一本很大的字典。