Search code examples
djangovalidationmodelvalidationerror

Django: how to raise a validation error exception in a model's save method?


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.


Solution

  • 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, on the model’s clean method, or by adding validators to the model’s fields. Then call save() only if the model form data is valid, in which case it is 'good enough to save'.