2014-01-16 58 views
0

這裏是如何MinLengthValidator在Django的定義:Django的:改變MinLengthValidator錯誤消息

class MinLengthValidator(BaseValidator): 
    compare = lambda self, a, b: a < b 
    clean = lambda self, x: len(x) 
    message = ungettext_lazy(
     'Ensure this value has at least %(limit_value)d character (it has %(show_value)d).', 
     'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).', 
     'limit_value') 
    code = 'min_length' 

我試着在我的代碼更改錯誤信息是這樣的:

password_min_length_validator = MinLengthValidator(8) 
password_min_length_validator.message = ungettext_lazy(
    'Ensure password has at least %(limit_value)d character (it has %(show_value)d).', 
    'Ensure password has at least %(limit_value)d characters (it has %(show_value)d).', 
    'limit_value') 

但我得到這個錯誤:

ugettext() takes exactly 1 argument (3 given) 

我這樣做就像django.core.validators那樣做。

+0

請提供完整的堆棧跟蹤。 – Serafeim

回答

0

看起來您使用的是早期版本的Django,因此您應該將代碼基於您的Django版本的MinLengthValidator,而不是當前的實現。由於在Django 1.6中更改了ungettext_lazy方法,因此您會收到錯誤消息(請參見憑證#19160)。

例如,在Django 1.5.X,你會怎麼做:

from django.utils.translation import ugettext_lazy as _ 

class MinLengthValidator(BaseValidator): 
    compare = lambda self, a, b: a < b 
    clean = lambda self, x: len(x) 
    message = _('Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).') 
    code = 'min_length' 

password_min_length_validator = MinLengthValidator(8) 
password_min_length_validator.message = _(
    'Ensure password has at least %(limit_value)d characters (it has %(show_value)d).', 
) 

而不是設置消息你實例驗證後屬性的,你可以繼承它:

class MyMinLengthValidator(MinLengthValidator): 
    message = _('Ensure my_field has at least %(limit_value)d characters (it has %(show_value)d).') 

my_min_length_validator = MyMinLengthValidator(8) 

另外,您可以在表單字段上使用error_messages選項:

class MyForm(forms.Form): 
    my_field = forms.CharField(validators=[MinLengthValidator(8)], 
         error_messages={'min_length': _('Ensure my_field has at least %(limit_value)d characters (it has %(show_value)d).') 
})