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')
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