Django:正确显示formset错误

Mon*_*lik 20 django django-templates django-forms

我有一个模型的内联formset,它有一个unique_together约束.因此,当我输入不满足此约束的数据时,它会显示:

__all__Please correct the duplicate values below.

代码,这是:

    {% for error in formset.errors %}
        {{ error }}<br/>
    {% endfor %}
Run Code Online (Sandbox Code Playgroud)

我不太喜欢__all__错误的开头,它很明显是字典键,所以我试过:

    {% for key, error in formset.errors %}
        {{ key }}: {{ error }}<br/>
    {% endfor %}
Run Code Online (Sandbox Code Playgroud)

但是我得到的只是:

__all__:

{{error}}根本不会显示.那么这里发生了什么?如何正确显示错误?

TM.*_*TM. 31

我认为这里的问题是formset.errors字典列表,而不是单个字典.

formset上Django文档页面:

>>> formset.errors
[{}, {'pub_date': [u'This field is required.']}]
Run Code Online (Sandbox Code Playgroud)

看看这样的东西是否解决了问题:( 根据askers评论更新)

{% for dict in formset.errors %}
    {% for error in dict.values %}
        {{ error }}
    {% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

如果失败了,我会尝试使用manage.py shell,并尝试在python shell中重现你的情况......这样就可以很容易地检查各种值并找出你需要做什么.


小智 9

for循环是不必要的,应该使用以下内容正确显示这些错误:

{{ formset.non_form_errors }}
Run Code Online (Sandbox Code Playgroud)


dsa*_*laj 5

Here is a clarification for anyone encountering similar issues of errors not being rendered in template:

If you have and error regarding the formset as a whole, use:

{{ formset.non_form_errors }}
Run Code Online (Sandbox Code Playgroud)

this basically returns errors in __all__ entry from formset.errors. It is documented as:

    """
    Returns an ErrorList of errors that aren't associated with a particular
    form -- i.e., from formset.clean(). Returns an empty ErrorList if there
    are none.
    """
Run Code Online (Sandbox Code Playgroud)

However if you are rendering forms from formset and some errors are not being renderd, you are probably missing:

{% for form in formset.forms %}
    {# ... #}
    {{ form.non_field_errors }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

this returns errors in __all__ entry from form.errors. Those are, analogous to the non_form_errors, the errors that aren't associated with a particular field, but rather with the field relations. For example if you had a form with fields From and To, and you validate if From value is smaller then To value, the tag {{ form.non_field_errors }} could render the following error:

'The From value must be smaller than the To value'
Run Code Online (Sandbox Code Playgroud)