How do you use django 1.2 form validators?

I am trying to use the new validators that are now included in Django. I set the validators parameter in my fields, and although I am not getting an error, validation does not work. Here is my console session that duplicates the problem.

  Python 2.7 (r27: 82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32 
 Type "help", "copyright", "credits" or "license" for more information. 
 (InteractiveConsole)
 >>> import django
 >>> django.VERSION
 (1, 2, 1, 'final', 0)
 >>> from django.core import validators
 >>> from django import forms
 >>> field = forms.CharField (validators = [validators.MinValueValidator (2)])
 >>> field.clean ("s") 
 u's'

I would expect field.clean("s") throw a validation exception because there is only one character in the string. I understand that it is possible that I misunderstand how to use validators, so any help would be greatly appreciated.

+4
source share
1 answer

I think you want to try MinLengthValidator instead of MinValueValidator .

MinValueValidator checks that the field value is greater than or equal to the specified value.

 >>> 's' > 2 True 

Since "s" > 2 , a validation error does not occur.

It would be wiser to use a MinValueError with an IntegerField or FloatField .

 >>> field = forms.FloatField(validators=[validators.MinValueValidator(2)]) >>> field.clean(5) 5.0 >>> field.clean(1.9) ... ValidationError: [u'Ensure this value is greater than or equal to 2.'] 

To ensure that the string has a specific length, use the MinLengthValidator .

 >>> field = forms.CharField(validators=[validators.MinLengthValidator(2)]) >>> field.clean('abc') u'abc' >>> field.clean('s') ... ValidationError: [u'Ensure this value has at least 2 characters (it has 1).'] 
+6
source

All Articles