Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addHow to make django post_save signal run only during creation

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')  
like image 486
HackAfro Avatar asked Jan 08 '17 13:01

HackAfro


People also ask

What is pre save signal in Django?

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.

What is the use of the Post_delete signal in Django?

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.

How does signal work in Django?

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.


1 Answers

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
like image 198
utkbansal Avatar answered Oct 24 '22 20:10

utkbansal