[Django]-Cancel saving model when using pre_save in django

28đź‘Ť

âś…

See my another answer: https://stackoverflow.com/a/32431937/2544762

This case is normal, if we just want to prevent the save, throw an exception:

from django.db.models.signals import pre_save, post_save

@receiver(pre_save)
def pre_save_handler(sender, instance, *args, **kwargs):
    # some case
    if case_error:
        raise Exception('OMG')
👤Alfred Huang

15đź‘Ť

I’m not sure you can cancel the save only using the pre_save signal. But you can easily achieve this by overriding the save method:

def save(self):
    if some_condition:
        super(A, self).save()
    else:
       return   # cancel the save

As mentioned by @Raptor, the caller won’t know if the save was successful or not. If this is a requirement for you, take look at the other answer which forces the caller to deal with the “non-saving” case.

👤Seb D.

5đź‘Ť

If the data’s always coming from a Form and you have a straightforward test for whether or not the save should occur, send it through a validator. Note, though, that validators aren’t called for save() calls originating on the backend. If you want those to be guarded as well, you can make a custom Field, say class PrimeNumberField(models.SmallIntegerField) If you run your test and raise an exception in the to_python() method of that custom field, it will prevent the save. You can also hook into the validation of a specific field by overriding any of several other methods on the Field, Form, or Model.

👤Sarah Messer

Leave a comment