Adding Model Field Validation to the Django Admin Page

Django, the hot Python web application framework, provides an excellent administration user interface out of the box. Django originated in the newsroom and it’s reflected throughout the code. The idea behind including an admin interface is that reporters can work on easily submitting their content while the code jockeys work on the fun stuff - namely presenting that content to their readers.

The admin interface provides a great experience out of the box but is also extensible so you can add features not present in the original interface.

I was working on a Model that was meant to be manipulated inside the admin interface. I wanted to provide constraints on some Integers Fields in that that model in order to limit the range of possible entered values.

The first way I tried to solve this was to add a choices parameter for my IntegerFields. While this technique worked, it caused my admin interface to add a drop down box displaying my choices. This was not what I was looking for.

The final way I solved it came from a suggestion on the Django IRC channel. Use validators. It took some digging through the documentation but I figured out how to do what I want. I will explain by way of an example.

from django.core import validators
from django.db import models

range_validator = validators.NumberIsInRange(0,4)

class Test (models.Model):
    valid_int = models.IntegerField(null=True, blank=True, validator_list=[range_validator])

The validation framework is defined in the validators module. Import that if you need to perform any validation on your data.

Django includes a number of built-in validators. I lucked out and they had a validator that suited my purposes. The first step creates a validator instance of NumberIsInRange with the appropriate range. This returns a callable that I use later.

Model fields take a parameter of type validator_list which is a “list of extra validators to apply to the field. Each should be a callable that takes the parameters field_data, all_data and raises django.core.validators.ValidationError for errors. (See the validator docs.)”

A quick test in the admin interface and the code works.

The Django documentation contains everything you need to get the job done. Some careful searching and a great support community has helped make Django one of the best web frameworks available.

[tags]django,framework,tutorial[/tags]

Joe Cotellese @JoeCotellese