Self-Validating Django Models – A Quick Tutorial

Jim King

Jim King

Questions about Django’s ability to save() when specifying valid choices on fields turn up in multiple posts throughout the internet. The answer is always the same: you have to implement it yourself. Below we discuss the how-to of self-validating Django models.

You see, Django models allow you to specify valid choices on fields, however when you call save() there is no validation that runs. A model that allows for violation of its own rules is absurd, but that is Django’s default behavior. To validate a model one must run the full_clean() method.

To solve this horrible behavior, we at CloudTruth implemented an abstract model base that ensures the model is validated on every save:

class SelfValidatingModel(Model):
    """
    This base ensures all saved objects are validated.

    Django does not do this by default!
    """
    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        self.full_clean()
        return super().save(*args, **kwargs)

If you derive your models from this class, you can be certain they will validate themselves before they go to the database.

For more tutorials or information about us, visit us at https://cloudtruth.com/.


About the Author: Jim King is a software engineer, architect, startup founder, and a maintainer on open source projects including Apache Thrift and the Boost C++ Libraries.