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')
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.
- [Django]-Accessing the object in a django admin template
- [Django]-Django Aggregation: Sum return value only?
- [Django]-How to redirect to previous page in Django after POST request
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.
- [Django]-Django MultiValueDictKeyError error, how do I deal with it
- [Django]-Django – how to make ImageField/FileField optional?
- [Django]-Login Page by using django forms