Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising ValidationError from django model's save method?

Tags:

python

django

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

like image 271
slypete Avatar asked Sep 24 '09 20:09

slypete


People also ask

What does save () do in Django?

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.

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.

Which method is used to save a model in DB in Python?

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.

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() .


1 Answers

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.

like image 166
Cerin Avatar answered Oct 21 '22 07:10

Cerin