Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 433
Bastian Avatar asked Jan 07 '12 16:01

Bastian


People also ask

How do I display validation error in Django?

To display the form errors, you use form. is_valid() to make sure that it passes validation. Django says the following for custom validations: Note that any errors raised by your Form.

How do I increase validation error in Django admin?

In django 1.2, model validation has been added. You can now add a "clean" method to your models which raise ValidationError exceptions, and it will be called automatically when using the django admin. The clean() method is called when using the django admin, but NOT called on save() .

How do you override the Save method of a model?

save() method from its parent class is to be overridden so we use super keyword. slugify is a function that converts any string into a slug. so we are converting the title to form a slug basically.

How do I save models in Django?

Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.


1 Answers

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'.

like image 112
Alasdair Avatar answered Sep 18 '22 12:09

Alasdair