Search code examples
djangodjango-signals

Connecting to signals sent by specific senders do not work as expected


I have models strucute as below

class WalletTransactions(models.Model):
     ...
     fields here    
     ...

class WalletBalance(models.Model):
     ...
     fields here    
     ...    

Signal handler like below

@receiver(post_save, sender=WalletTransactions)
def update_balance(sender, instance, created, **kwargs):
    print instance.payment_type #field in model

And finally registration

post_save.connect(update_balance, dispatch_uid=uuid.uuid4())

Now I am expecting update_balance to be called only when save on WalletTransaction is called as per doc.

But when I am trying to login to my application, the update_balance is being called when save on Session is called throwing following error.

AttributeError at /login/
'Session' object has no attribute 'payment_type'

What could be the mistake here?


Solution

  • You are connecting you callback function twice. You can either connect the signal with @receiver or with post_save.connect.

    See here for more information: https://docs.djangoproject.com/en/1.11/topics/signals/#connecting-receiver-functions

    Additionally, you didn't specify a sender in post_save.connect(). So basically you connect the callback to the save method of every object.

    To make it work simply remove this line:

    post_save.connect(update_balance, dispatch_uid=uuid.uuid4())