I have a model:
class A(models.Model): number = models.IntegerField()
But when I call A.save(), I want to ensure that number is a prime (or other conditions), or the save instruction should be cancelled.
So how can I cancel the save instruction in the pre_save signal receiver?
@receiver(pre_save, sender=A) def save_only_for_prime_number(sender, instance, *args, **kwargs): # how can I cancel the save here?
When you overwrite a function (of a class) you can call the function of the parent class using super . The save function in the models records the instance in the database. The first super(Review, self). save() is to obtain an id since it is generated automatically when an instance is saved in the database.
pre_save) is provoked just before the model save() method is called, or you could say model save method is called only after pre_save is called and done its job free of errors.
You can use pre_save for example if you have a FileField or an ImageField and see if the file or the image really exists. You can use post_save when you have an UserProfile and you want to create a new one at the moment a new User it's created.
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')
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.
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