Use signals in Django 1.9

我与影子孤独终老i 提交于 2019-12-10 10:04:23

问题


In Django 1.8, I was able to do the following with my signals, and all was well:

__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)

In Django 1.9, I get this error: 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? I'm assuming maybe putting it in the models? If so, could someone please show me how to do that?

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!


回答1:


From the 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.

By importing your signals in __init__.py, you're indirectly importing your models in the root package of your application. One option to avoid this is to change the sender to a string:

@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().



来源:https://stackoverflow.com/questions/34301070/use-signals-in-django-1-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!