Javier Cárdenas Javier Cárdenas - 1 month ago 12
Python Question

DecimalField Validation in Django

I'm trying to validate a

DecimalField
in Django

Trying in shell:

>> from django.forms import DecimalField
>> from django.core.validators import MaxValueValidator
>> f = DecimalField(max_digits=2, decimal_places=1, validators=[MaxValueValidator(10)])
>> f.validate(11) # after this I should get an error
>>


But it does not show validation errors. It should throw an error because 11 is greater that 10, right?

What I'm doing wrong?

Answer

You are 1 problem in field declaration. if max_digits = 2 and decimal_places = 1, your max is 9.9 without the intervention of validators.

max_digits = 3 and validators for max = 10.0

Use clean() function:

>> from django.forms import DecimalField
>> from django.core.validators import MaxValueValidator
>> f = DecimalField(max_digits=3, decimal_places=1, validators [MaxValueValidator(10)])
>> f.clean(11.2)

https://docs.djangoproject.com/en/1.10/ref/forms/validation/

Comments