简体   繁体   English

在Django 1.9中使用信号

[英]Use signals in Django 1.9

In Django 1.8, I was able to do the following with my signals, and all was well: 在Django 1.8中,我能够用我的信号执行以下操作,一切都很顺利:

__init__.py: __init__.py:

from .signals import *

signals.py: 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)

In Django 1.9, I get this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. 在Django 1.9中,我收到此错误: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

I know it's coming from the __init__.py , but does anyone know a workaround for this? 我知道它来自__init__.py ,但有没有人知道解决方法呢? I'm assuming maybe putting it in the models? 我假设可能把它放在模型中? If so, could someone please show me how to do that? 如果是这样,有人可以告诉我该怎么做吗?

models.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

Thank you in advance! 先感谢您!

From the release notes : 发行说明

All models need to be defined inside an installed application or declare an explicit app_label. 所有模型都需要在已安装的应用程序中定义,或者声明一个显式的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. 特别是,无法在应用程序的根包中导入模型。

By importing your signals in __init__.py , you're indirectly importing your models in the root package of your application. 通过在__init__.py导入信号,您可以在应用程序的根包中间接导入模型。 One option to avoid this is to change the sender to a string: 避免这种情况的一个选择是将sender更改为字符串:

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

The recommended way to connect signals that use @receiver decorator in 1.9 is to create an application configuration , and import the signals module in AppConfig.ready() . 在1.9中连接使用@receiver装饰器的信号的推荐方法是创建应用程序配置 ,并在AppConfig.ready()导入信号模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM