2011-04-01 37 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