Full answer
Three layers check data:
- Field-level:
max_length,null,choices, andvalidators=[...]such asMinValueValidator(0),RegexValidatoror your own function that raisesValidationError. - Model-level: override
clean()for rules that involve several fields, and raiseValidationError({"end": "End must be after start"})to attach the error to a field. - Database-level:
UniqueConstraint,CheckConstraint,NOT NULL, foreign keys.
full_clean() runs clean_fields(), then clean(), then validate_unique() and validate_constraints(), and raises a single ValidationError holding all messages (exc.message_dict). ModelForm and the admin call it, so form submissions get friendly errors.
save() does not call it, because validation costs queries and not every write needs it. Code such as Student.objects.create(score=-5) happily writes bad data if only Python validators protect it. Therefore:
- Call
obj.full_clean()beforesave()in your own services, or validate through a Form or serializer. - Put hard invariants in
CheckConstraintso the database rejects bad rows, and bulk operations or raw SQL cannot bypass it. blank=Trueis validation-only (can the form be empty);null=Trueis a database setting. Text fields normally useblank=Truewithoutnull=True.
Validators run in migrations as part of the field definition, so keep validator functions importable at module level (not lambdas or local functions).
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models, connection, IntegrityError
class Exam(models.Model):
title = models.CharField(max_length=30)
marks = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)])
start = models.IntegerField()
end = models.IntegerField()
class Meta:
app_label = "school"
constraints = [models.CheckConstraint(condition=models.Q(marks__gte=0), name="marks_not_negative")]
def clean(self):
if self.end <= self.start:
raise ValidationError({"end": "End must be after start."})
with connection.schema_editor() as editor:
editor.create_model(Exam)
bad = Exam(title="Unit test", marks=150, start=10, end=5)
try:
bad.full_clean()
except ValidationError as exc:
print(exc.message_dict)
Exam(title="Quiz", marks=150, start=1, end=2).save() # save() does not validate
print("saved marks:", Exam.objects.get().marks)
try:
Exam.objects.create(title="Broken", marks=-1, start=1, end=2)
except IntegrityError as exc:
print("database refused:", type(exc).__name__)
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. CheckConstraint uses condition=, the keyword since Django 5.1 (check= was removed in 6.0). Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): {'marks': ['Ensure this value is less than or equal to 100.'], 'end': ['End must be after start.']} saved marks: 150 database refused: IntegrityError
Key points
- Validators run in full_clean(), not in save()
- clean() handles cross-field rules
- ValidationError can be attached to a field via a dict
- CheckConstraint enforces rules for every write path
- blank is for validation, null is for storage
Common mistakes
- Assuming save() or create() runs validators
- Relying on validators alone for invariants that must always hold
- Using null=True on CharField instead of blank=True
- Using lambdas as validators, which cannot be serialised in migrations
Follow-ups
- How do ModelForms report errors from clean()?
- What does validate_constraints() do?
- How do you validate in a DRF serializer instead?
Tips
- Say which method calls what
- Point out the database as final defence
- Distinguish blank and null