Richard Knop
Richard Knop

Reputation: 83695

Django: Change MinLengthValidator Error Message

Here is how MinLengthValidator is defined in Django:

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'

I tried changing the error message in my code like this:

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')

But I am getting this error:

ugettext() takes exactly 1 argument (3 given)

I am doing it the same way django.core.validators does it.

Upvotes: 0

Views: 2804

Answers (1)

Alasdair
Alasdair

Reputation: 308889

It looks like you're using an earlier version of Django, so you should base your code on the MinLengthValidator for your Django version, and not the current implementation. You are getting the error because the ungettext_lazy method changed in Django 1.6 (see ticket #19160).

For example, in Django 1.5.X, you would do:

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).',
)

Instead of setting the messages attribute after you instantiate the validator, you could subclass it:

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)

Alternatively, you could use error_messages option on the form field:

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).')
})

Upvotes: 2

Related Questions