liveBook · Manning

ValidationError

As explained in Django in Action

ValidationError is a Django exception indicating that a value or object fails validation.

ValidationError is Django’s signal that a value or object fails validation. In model validation, it is especially useful when fields depend on one another rather than merely rejecting empty or malformed individual values. section 7.2.1

Override a model’s clean() method, check the relationship between fields, and raise ValidationError when the combination is invalid. For example, a SeekingAd can require a band when seeking a musician. section 7.2.1

Validating a SeekingAd

def clean(self): if self.seeking == MusicianBandChoice.MUSICIAN: if self.band is None: raise ValidationError( "Band field required when seeking a musician") Django calls clean() when using the Admin, but creating an object directly in the REPL does not call it automatically. Override save() to call clean() if programmatic creation must enforce the rule. section 7.2.1

How Django in Action covers it

How deep it goes
Explains custom clean() checks and the important limitation that clean() is not called automatically everywhere.
Examples
Demonstrates a SeekingAd requiring a Band when its seeking choice is MUSICIAN.
What it assumes
Assumes basic Django model fields and constraints, then extends validation to relationships between fields.
What you can do after
Build custom model validation by raising ValidationError from clean() when related fields contain an invalid combination.
How it connects
Connects ValidationError with Django models, clean(), field validation, model relationships, and the Django Admin.

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.