【问题标题】:Why does the signal not trigger?为什么信号不触发?
【发布时间】:2017-03-16 11:30:22
【问题描述】:

在上面坐了一天。真的无法理解为什么在激活用户时没有触发此信号,没有错误日志,激活时管理员没有异常。有人可以帮忙吗?下面的代码应该会在 apache error.log 中产生用户时的日志消息,对吧?

import logging
from django.dispatch import receiver
from registration.signals import user_activated

@receiver(user_activated)
def registered_callback(sender, **kwargs):
    logger = logging.getLogger("user-activated")
    logger.error("activated here")

user_registered相同

【问题讨论】:

    标签: django signals django-registration django-signals


    【解决方案1】:

    首先我使用 django 1.8.3 。你应该先注册你的信号。据我所知,有一些方法可以做到这一点,但这就是我正在做的; 在您的应用中创建signals.py 并在其中写入您的信号;

    from django.db.models.signals import post_save
    from django.dispatch import receiver
    @receiver(post_save, sender=your_model,dispatch_uid="yourmodel_save_receiver")
                def post_save_yourmodel(sender, instance, **kwargs):
                     if instance.profile_status:
                         print "active"
                     else:
                         print "not active"
    

    那么你应该创建apps.py。此文件包含模型的配置信息。

    from django.apps import AppConfig
    class yourmodel_config(AppConfig):
        name = 'yourmodel_config'
        verbose_name = 'your_model config'
    
        def ready(self):
            import yourmodel.signals
    

    只要您的应用准备就绪,您的信号就会被导入 最后打开你的__init__.py 并添加以下内容。

    default_app_config = 'yourmodel.apps.yourmodel_config'
    

    通过这个,您可以为您的模型定义应用程序配置。此示例在保存yourmodel 时,会检查profile_status 属性并根据值(true 或false)将输出打印到您的控制台。您还可以将created 参数添加到您的模型中,以了解是否创建了模型实例。如果创建了新记录,created 将返回 True。 def post_save_yourmodel(sender, instance, created, **kwargs):。否则,只要您的模型使用yourmodel.save() 保存,就会触发此信号。 考虑这是一个post_save 示例。您可以从here 找到模型信号列表。

    【讨论】:

    • 如果我理解正确,您描述了如何制作新信号,对吗?不过,我使用的是预定义的。如果我没有做错什么,那么我正在使用的那个框架中有一个错误(django-registration,或者我为它们使用的模板)。所以,这个问题更像是“你看到拼写错误还是你也认为这是一个错误?”
    • 是的,这就是实现新信号的方式。我不认为你的问题是一个错误。您必须像 post_save.connect(registered_callback,sender=mymodel) 那样以某种方式签署您的接收器到应用程序。也许这就是为什么你的接收器没有捕捉到任何信号,但我对你的方法没有经验,所以我不太确定你的问题是什么。
    • 那么,您如何解释registration documentation?我会说他们对已经实施的信号非常有信心。只要我不注册第二个,其中一个甚至可以工作。我不认为添加接收应该删除或副作用不触发另一个。
    猜你喜欢
    • 1970-01-01
    • 2011-02-27
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多