Django:如何覆盖unique_together错误消息? [英] Django: How to override unique_together error message?

查看:621
本文介绍了Django:如何覆盖unique_together错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在模型的Meta类中,我定义了一个unique_together。我有一个基于此模型的ModelForm。当我在此ModelForm上调用is_valid时,如果unique_together验证失败,则会自动引发错误。这很好。

In a model's Meta class, I define a unique_together. I have a ModelForm based on this model. When I call is_valid on this ModelForm, an error will automatically raised if unique_together validation fails. That's all good.

现在我的问题是我对默认的unique_together错误消息不满意。我想覆盖它。我怎样才能做到这一点?对于一个字段相关的错误,我可以很方便地通过在field参数中设置error_messages来做到这一点。但是unique_together是一个非字段错误。如何覆盖非字段错误消息?

Now my problem is that I'm not satisfied with the default unique_together error message. I want to override it. How can I do that? For a field related error, I can easily do that by setting error_messages on the field parameters. But unique_together is a non field error. How can I override a non field error message?

推荐答案

注意: Django中有很多变化因为这个答案。所以更好的检查其他答案...

Notice: A lot had changed in Django since this answer. So better check other answers...

如果sebpiq是真的(因为我不检查源代码),那么有一个
可能的解决方案,你可以做,但这是很难的方式...

If what sebpiq is true( since i do not check source code), then there is one possible solution you can do, but it is the hard way...

您可以在您的表单中定义验证规则,如这里所述

You can define a validation rule in your form, as it described here

你可以看到示例有多个字段的验证,所以通过使用此方法,您可以在执行标准django唯一检查之前定义唯一的一起检查...

You can see examples of validation with more than one field, so by using this method, you can define a unique together check before standard django unique check executed...

或最糟糕的一个,您可以在尝试保存对象之前在您的视图中进行验证。

Or the worst one, you can do a validation in your view before you try to save the objects...

这篇关于Django:如何覆盖unique_together错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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