2011-04-01 39 views
14

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

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 

这是不是很方便,所以我想重写它...

+0

'unique'是现场选项:http://docs.djangoproject.com/en/1.3/ref/models/fields/#unique – Rob 2011-04-01 14:34:34

+0

在你的标题你在谈论的IntegrityError,当尝试保存具有不唯一值的实例时引发这个问题,请参阅:http://docs.djangoproject.com/en/dev/ref/models/fields/#unique – Bjorn 2011-04-01 14:36:26

+0

@Bjorn,也许我的标题有点混乱。我修改了它。我想重写标准错误消息,但我不知道错误消息的名称。我认为它被称为“独特”,但也许不是。也许我不能用这种方式重写它? – 2011-04-01 14:46:04

回答

6

这个错误信息显然是在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时,它可能会破坏事物。

+0

没错。谢谢。我也发现这张票http://code.djangoproject.com/ticket/8913希望这将实施一天... – 2011-04-01 15:01:37

0

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

23

非常感谢。

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

现在这工作得很好。

如果你想定制error_messages像invalided,在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."}) 
+0

这在django 1.8中工作吗? – aldesabido 2016-07-15 06:17:03