簡體   English   中英

在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

先感謝您!

發行說明

所有模型都需要在已安裝的應用程序中定義,或者聲明一個顯式的app_label。 此外,在加載應用程序之前無法導入它們。 特別是,無法在應用程序的根包中導入模型。

通過在__init__.py導入信號,您可以在應用程序的根包中間接導入模型。 避免這種情況的一個選擇是將sender更改為字符串:

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

在1.9中連接使用@receiver裝飾器的信號的推薦方法是創建應用程序配置 ,並在AppConfig.ready()導入信號模塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM