显示唯一字段的Django错误消息

时间:2011-04-01 14:15:27

标签: django django-models

我想更改默认错误消息,当重复条目尝试保存时,它们应该是唯一的,即unique=True。很像这样:

email = models.EmailField(unique=True, error_messages={'unique':"This email has already been registered."})

但是,上述案例中的unique是猜测,并不起作用。我也无法找出错误的名称实际上是什么。有谁知道正确的名字?

请注意,此验证是模型级别,而不是表单验证。

编辑: 更多信息,目前form.errors显示当前错误消息:

[model_name] with this [field_label] already exists

哪个用户不太友好,所以我想覆盖它......

4 个答案:

答案 0 :(得分:36)

非常感谢。

email = models.EmailField(unique=True, error_messages={'unique':"This email has already been registered."})

现在效果非常好。

如果您想自定义invalided之类的error_messages,请在forms.ModelForm

中执行
email = forms.EmailField(error_messages={'invalid': 'Your email address is incorrect'})

但是unique字段应该在model字段中进行自定义,如上所述

email = models.EmailField(unique=True, error_messages={'unique':"This email has already been registered."})

答案 1 :(得分:7)

此错误消息显然是在django / db / models / base.py文件中进行了硬编码。

def unique_error_message(self, model_class, unique_check):
    opts = model_class._meta
    model_name = capfirst(opts.verbose_name)

    # A unique field
    if len(unique_check) == 1:
        field_name = unique_check[0]
        field_label = capfirst(opts.get_field(field_name).verbose_name)
        # Insert the error into the error dict, very sneaky
        return _(u"%(model_name)s with this %(field_label)s already exists.") %  {
            'model_name': unicode(model_name),
            'field_label': unicode(field_label)
        }
    # unique_together
    else:
        field_labels = map(lambda f: capfirst(opts.get_field(f).verbose_name), unique_check)
        field_labels = get_text_list(field_labels, _('and'))
        return _(u"%(model_name)s with this %(field_label)s already exists.") %  {
            'model_name': unicode(model_name),
            'field_label': unicode(field_labels)
        }

解决此问题的一种方法是创建从EmailField派生的自定义模型,并覆盖unique_error_message方法。但请注意,当您升级到较新版本的Django时,它可能会破坏。

答案 2 :(得分:1)

自Django 1.4以来,您提供的确切示例实际上有效。也许他们找到了您的错误报告并修复了它?

https://github.com/django/django/blob/1.4.20/django/db/models/base.py#L780

答案 3 :(得分:0)

唯一错误消息由django.db.models.base.unique_error_message构建(至少在Django 1.3上)。

相关问题