Raise a validation error in a model's save method in Django

Bastian picture Bastian · Jan 7, 2012 · Viewed 66k times · Source

I'm not sure how to properly raise a validation error in a model's save method and send back a clear message to the user.

Basically I want to know how each part of the "if" should end, the one where I want to raise the error and the one where it actually saves:

def save(self, *args, **kwargs):
    if not good_enough_to_be_saved:
        raise ValidationError
    else:
        super(Model, self).save(*args, **kwargs)

Then I want to know what to do to send a validation error that says exactly to the user what's wrong just like the one Django automatically returns if for example a value is not unique. I'm using a (ModelForm) and tune everything from the model.

Answer

Alasdair picture Alasdair · Jan 7, 2012

Most Django views e.g. the Django admin will not be able to handle a validation error in the save method, so your users will get 500 errors.

You should do validation on the model form or on the model, and raise ValidationError there. Then call save() only if the model form data is 'good enough to save'.