获取Django表单中的错误列表 [英] Getting a list of errors in a Django form

查看:441
本文介绍了获取Django表单中的错误列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Django中创建一个表单。这个工作和所有,但我希望所有的错误在表单的顶部,而不是在每个有错误的字段旁边。我尝试循环使用form.errors,但是它只显示了有错误的字段的名称,而不是需要名称的错误消息。



几乎是我想要在表单顶部使用的:

  {%if form。 ?? %} 
< ul class =errorlist>
{%表示错误? %}
< li> {{error}}< / li>
{%endfor%}
< / ul>
{%endif%}

我将在中使用什么? ?? 那里?不是错误;只需输出字段的名称。

解决方案

form.errors是一个字典。当你做 {%for form.errors%} 错误对应于密钥。



而是尝试

  {%for field,form.errors.items%} 
{%错误错误%}
...

等等。


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 is a dictionary. When you do {% for error in form.errors %} error corresponds to the key.

Instead try

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

Etc.

这篇关于获取Django表单中的错误列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆