在 Django 1.9 中使用信号

Use signals in Django 1.9

在 Django 1.8 中,我可以使用我的信号执行以下操作,并且一切正常:

__init__.py:

from .signals import *

signals.py:

@receiver(pre_save, sender=Comment)
def process_hashtags(sender, instance, **kwargs):
    html = []
    for word in instance.hashtag_field.value_to_string(instance).split():
        if word.startswith('#'):
            word = render_to_string('hashtags/_link.html',
                                    {'hashtag': word.lower()[1:]})

        html.append(word)
        instance.hashtag_enabled_text = ' '.join(html)

在 Django 1.9 中,我得到这个错误:django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

我知道它来自 __init__.py,但有人知道解决方法吗?我假设也许把它放在模型中?如果是这样,有人可以告诉我该怎么做吗?

models.py:

class Comment(HashtagMixin, TimeStampedModel):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    text = models.TextField(max_length=240)
    hashtag_enabled_text = models.TextField(blank=True)
    hashtag_text_field = 'text'

    objects = CommentManager()

    class Meta:
        app_label = 'comments'

    def __unicode__(self):
        return self.text

提前致谢!

来自release notes

All models need to be defined inside an installed application or declare an explicit app_label. Furthermore, it isn’t possible to import them before their application is loaded. In particular, it isn’t possible to import models inside the root package of an application.

通过在 __init__.py 中导入您的信号,您将在您的应用程序的根包中间接导入您的模型。避免这种情况的一种选择是将 sender 更改为字符串:

@receiver(pre_save, sender='<appname>.Comment')
def process_hashtags(sender, instance, **kwargs):
    ...

在 1.9 中连接使用 @receiver 装饰器的信号的推荐方法是创建一个 application configuration,并在 AppConfig.ready() 中导入信号模块。