← Back to Django, page 3

django-0059 · Easy fresher

How does validation work on Django models: field validators, clean() and full_clean(), and why does save() not validate?

Field validators and clean()/clean_fields()/validate_unique() run when you call full_clean(), which ModelForms and the admin call for you. Model.save() does not call full_clean(), so writing through the ORM or a custom view skips validation unless you call it. Database constraints are the last line of defence because they always apply.

Full answer

Three layers check data:

  1. Field-level: max_length, null, choices, and validators=[...] such as MinValueValidator(0), RegexValidator or your own function that raises ValidationError.
  2. Model-level: override clean() for rules that involve several fields, and raise ValidationError({"end": "End must be after start"}) to attach the error to a field.
  3. 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() before save() in your own services, or validate through a Form or serializer.
  • Put hard invariants in CheckConstraint so the database rejects bad rows, and bulk operations or raw SQL cannot bypass it.
  • blank=True is validation-only (can the form be empty); null=True is a database setting. Text fields normally use blank=True without null=True.

Validators run in migrations as part of the field definition, so keep validator functions importable at module level (not lambdas or local functions).

python
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