如何断开django信号?

时间:2015-10-28 22:42:35

标签: python django model signals

我的MessageFolder模型中有一个信号可以正常工作,但在某些特殊情况下,我不希望发生post_save信号操作。在这种情况下如何停用它?

我尝试过以下但是它没有工作。

Views.py

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

        email_message = EmailMessage(
            subject,
            message,
            my_username,
            [recipent,],
            [],  # ['bcc@example.com'],
            headers = {'Reply-To': 'gusreyes01@example.com'}
        )

        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

1 个答案:

答案 0 :(得分:3)

我使用了以下内容,它适用于我

断开:

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

连接:

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