I have model with a field validator
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
class MyModel(mode
From django documentation:
Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.
https://docs.djangoproject.com/en/3.1/ref/validators/#how-validators-are-run
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
Validators work only with the Forms and model forms. Can't be used with the model definition because it runs at the app side not the DB side.
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 ModelForm
s and save the model only when the form is valid.