Django post save signal getting called twice despite uid

前端 未结 4 1498
[愿得一人]
[愿得一人] 2020-12-16 21:59

I have registered my signal with the callback using the @receiver decorator

@receiver(post_save, sender=User, dispatch_uid=\'ARandomUniqueString         


        
4条回答
  •  北海茫月
    2020-12-16 22:31

    I just encountered the same problem. I have a receiver that does something important which must be done only once for each new creation of a model instance in Django. So, I used the post_save signal, but that was being called twice for the creation of each new model instance which I was doing like Profile.objects.create(...). The solution to this problem is the created flag which comes with kwargs. Here's how you can use that flag to make sure your intended action is taken only once:

    @receiver(post_save, sender=Profile)
    def publish_auction(sender, **kwargs):
        if kwargs['created']:
            kwargs['instance'].send_email_confirmation()
    

    I tried the dispatch_uid suggestion from Django docs. It didn't work, but the code I pasted above works.

提交回复
热议问题