About Model Field Validation

You can validate your model fields within the clean method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django.db import models
from django.core.exceptions import ValidationError

class Product(models.Model):
    ...
    slug = models.SlugField(_("Slug"), max_length=255, blank=True)

    def clean(self):
        if self.slug:
            # Check for uniqueness only if the slug is set
            if Opportunity.objects.filter(
                slug=self.slug,
            ).exclude(id=self.id).exists():
                raise ValidationError(
                    {"slug": "This slug is already in use."}
                )

When saving a model form of such a model, you will see normal form validation errors there.

Tips and Tricks Programming Django 5.x Django 4.2 Django 3.2