Django:正确显示表单集错误 [英] Django: Displaying formset errors correctly

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

问题描述

我有一个模型的内联表单集,它具有unique_together约束。因此,当我输入不满足此约束的数据时,它将显示:

I have an inline formset for a model, which has a unique_together constraint. And so, when I input data, which doesn't fulfill this constraint, it displays:

__ all__请更正以下重复的值。

__all__Please correct the duplicate values below.

代码是这样的:

    {% for error in formset.errors %}
        {{ error }}<br/>
    {% endfor %}

我不太喜欢 __ all __ 在错误开始处,并且很明显是字典键,所以我尝试了:

I don't much like the __all__ at the beginning of the error and it is quite clearly the dictionary key, so I tried:

    {% for key, error in formset.errors %}
        {{ key }}: {{ error }}<br/>
    {% endfor %}

但是我得到的只是:

__ all __:

__all__:

{{错误}}完全不会显示。那么这是怎么回事?以及如何正确显示错误?

{{ error }} won't display at all. So what's going on here? And how do I display the error correctly?

推荐答案

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

I think the problem here is that formset.errors is a list of dictionaries, not a single dictionary.

来自表单集上的Django文档页面

>>> formset.errors
[{}, {'pub_date': [u'This field is required.']}]

查看是否可以解决此问题:(根据询问者的评论更新

See if something like this fixes the problem: (Updated based on the askers comments)

{% for dict in formset.errors %}
    {% for error in dict.values %}
        {{ error }}
    {% endfor %}
{% endfor %}

如果失败,我会尝试使用 manage.py shell ,然后尝试在python shell中重现您的情况...那样可以很容易地检查各种值并弄清楚您需要做什么。

If that fails, I'd try using manage.py shell, and try to reproduce your situation in the python shell... that way it will be easy to inspect the various values and figure out what you need to do.

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

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