Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model validator not working on create

I have model with a field validator

from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator   class MyModel(model.Model):      name = models.CharField()      size = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(10)]) 

The validator is working well in the django admin panel ,while I try to enter the value more than 10, it's showing me the error message 'Ensure this value is less than or equal to 10' and does not allow to save.

But, when I try in the django shell, the validator is not working, it allows to save the record, I don't know why is the validator not throwing error message here.

>>>form app.models import MyModel >>>MyModel.objects.create(name="Some Name", size=15) <MyModel: Some Name> 

Can you please suggest me if anything I missed or any mistake i did here. Kindly help me to solve this problem, it will be very greatfull for me, Thanks in advance.

like image 995
Ajay Kumar Avatar asked Nov 30 '16 06:11

Ajay Kumar


2 Answers

Django validation is mostly application level validation and not validation at DB level. Also Model validation is not run automatically on save/create of the model. If you want to validate your values at certain time in your code then you need to do it manually.

For example:

from django.core.exceptions import ValidationError form app.models import MyModel  instance = MyModel(name="Some Name", size=15) try:     instance.full_clean() except ValidationError:     # Do something when validation is not passing else:     # Validation is ok we will save the instance     instance.save() 

More info you can see at django's documentation https://docs.djangoproject.com/en/1.10/ref/models/instances/#validating-objects

In administration it works automatically because all model forms (ModelForm) will run model validation process alongside form validation.

If you need to validate data because it is coming from untrusted source (user input) you need to use ModelForms and save the model only when the form is valid.

like image 127
VStoykov Avatar answered Oct 04 '22 12:10

VStoykov


The validator only works when you are using models in a ModelForm.

https://docs.djangoproject.com/en/dev/ref/validators/#how-validators-are-run

You can perform model validation by overidding clean() and full_clean() methods

like image 28
sunny Avatar answered Oct 04 '22 10:10

sunny