I need to raise an exception in a model's save method. I'm hoping that an exception exists that will be caught by any django ModelForm
that uses this model including the admin forms.
I tried raising django.forms.ValidationError
, but this seems to be uncaught by the admin forms. The model makes a remote procedure call at save time, and it's not known until this call if the input is valid.
Thanks, Pete
save() , django will save the current object state to record. So if some changes happens between get() and save() by some other process, then those changes will be lost.
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.
Save Your Model with pickle Pickle is the standard way of serializing objects in Python. You can use the pickle operation to serialize your machine learning algorithms and save the serialized format to a file.
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() .
Since Django 1.2, this is what I've been doing:
class MyModel(models.Model):
<...model fields...>
def clean(self, *args, **kwargs):
if <some constraint not met>:
raise ValidationError('You have not met a constraint!')
super(MyModel, self).clean(*args, **kwargs)
def full_clean(self, *args, **kwargs):
return self.clean(*args, **kwargs)
def save(self, *args, **kwargs):
self.full_clean()
super(MyModel, self).save(*args, **kwargs)
This has the benefit of working both inside and outside of admin.
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