How to add validation to a Django model field?

Published on Aug. 22, 2023, 12:19 p.m.

To add validation to a Django model field, you can use the validators argument of the field definition. The validators argument takes a list of callables and Django will run each validator on the field when you call full_clean() or validate() on the model instance.

Here’s an example of how to add a validator to a model field:

from django.core.exceptions import ValidationError
from django.db import models

def validate_even(value):
    if value % 2 != 0:
        raise ValidationError(
            '%(value)s is not an even number',
            params={'value': value},
        )

class MyModel(models.Model):
    my_field = models.IntegerField(validators=[validate_even])

In this example, we define a validator function validate_even() that checks if the field value is even. We then pass this validator function to the validators argument of the IntegerField definition for the my_field field in the MyModel model.

When you create a new instance of MyModel and set my_field to an odd number, Django’s validation system will raise a ValidationError.

Here’s an example of how to use model validation in a Django view:

from django.shortcuts import render
from myapp.models import MyModel

def my_view(request):
    if request.method == 'POST':
        my_field_value = request.POST['my_field']
        my_model = MyModel(my_field=my_field_value)
        try:
            my_model.full_clean()
        except ValidationError as e:
            # handle validation error
            pass
        else:
            # save the model
            my_model.save()
    else:
        return render(request, 'my_template.html')

In this example, when the user submits a form with a value for my_field, we create a new instance of MyModel, set my_field to the user-provided value, and call full_clean() on the model to run its validators. If full_clean() raises a ValidationError, we handle the error appropriately (e.g. by showing an error message to the user), otherwise we save the model instance.

Tags: