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.
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.
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() .
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.
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.
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With