Django save object to db if condition met

Viewed 121

I'm trying to use django pre_save signal to write the instance into db if a specific condition is met.

How can I achieve this ? I'm having a function handler which is called by pre_save and I want to drop saving the instance if a condition is not met.

I want to abort the whole save chain.

Is it pre_save signal the proper way to do this ?

1 Answers

You can raise an exception:

@receiver(pre_save, sender=MyModel)
def pre_save_handler(sender, instance, *args, **kwargs):
    # your logic
    if my_error:
        raise Exception('Aborting')

This should work, but keep in mind that this is supposed to be dealt with on your forms/serializer in your view, not in a signal

Related