I'm using django-notifications in my project and I want to notify a particular user whenever a model is created using the signal, but the post_save also runs when a model is being updated how do I prevent this and only make the post_save method run when a model is created.
models.py
class Card(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
title = models.CharField(max_length=100)
description = models.TextField(blank=True)
list = models.ForeignKey(List, related_name='cards')
story_points = models.IntegerField(null=True, blank=True)
business_value = models.IntegerField(null=True, blank=True)
def __str__(self):
return "Card: {}".format(self.title)
def my_handler(sender, instance, **kwargs):
if instance.pk is None:
notify.send(instance.user, recipient=User.objects.get(pk=1), target=instance, verb='created')
post_save.connect(my_handler, sender=Card)
I tried using if instance.pk is None, but when I add this condition it doesn't run at all.
EDITED: The code checking if created
def my_handler(sender, instance, created, **kwargs):
if created:
notify.send(instance.user, recipient=User.objects.get(pk=1), target=instance, verb='created')
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.
Django Signals - post_delete() To notify another part of the application after the delete event of an object happens, you can use the post_delete signal.
Django includes a “signal dispatcher” which helps decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place.
There is a created named argument which will be set to True if it's a new object.
Have a look here - https://docs.djangoproject.com/en/1.10/ref/signals/#post-save
def my_func(sender, instance, created, **kwargs):
print("Created: ", created)
class MyModel(models.Model):
x = models.CharField(max_length=255)
post_save.connect(my_func, sender=MyModel)
>>> MyModel.objects.create(f='asdf')
Created: True
>>> m = MyModel.objects.all().first()
>>> m.x
'asdf'
>>> m.x = 'a'
>>> m.save()
Created: False
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