Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disconnect a django signal?

I have a signal in my MessageFolder model which works fine, however in some special ocassions I don't want the post_save signal action to occur. How can I deactivate it in this case?

I have tried the following but it's not workign.

Views.py

        signals.post_save.disconnect(receiver=MessageFolder,sender=Message)

        email_message = EmailMessage(
            subject,
            message,
            my_username,
            [recipent,],
            [],  # ['[email protected]'],
            headers = {'Reply-To': '[email protected]'}
        )

        signals.post_save.connect(MessageFolder,MessageFolder.assign_message_folder)

        # Save it
        my_mailbox.record_outgoing_message(
            email_message.message()
        )

Models.py

class MessageFolder(models.Model):

folder        = models.ForeignKey(Folder, null = True, blank = True)
message       = models.ForeignKey(Message, null = True, blank = True)

@receiver((post_save), sender=Message, dispatch_uid="assign_message_folder")
def assign_message_folder(sender, instance, created, **kwargs):
    if not created: 
        return
    else:
        # generate MessageFolder && UserFolder
        if(instance.outgoing):
            message_folder = MessageFolder(None, 2, instance.pk)
        else:
            message_folder = MessageFolder(None, 1, instance.pk)

    message_folder.save()
    return
like image 752
Gustavo Reyes Avatar asked Oct 28 '15 22:10

Gustavo Reyes


1 Answers

I've used the following and it works for me

Disconnect:

signals.post_save.disconnect(assign_message_folder, sender=MessageFolder)

Connect:

signals.post_save.connect(assign_message_folder, sender=MessageFolder)
like image 170
Serjik Avatar answered Oct 07 '22 21:10

Serjik