在 Django 1.8 中,我能够使用信号执行以下操作,一切顺利:
__init__.py:
from .signals import *
信号.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
,但有人知道解决方法吗?我想也许可以把它放入模型中?如果是这样,有人可以告诉我该怎么做吗?
模型.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
先感谢您!
来自发行说明 https://docs.djangoproject.com/en/1.9/releases/1.9/#features-removed-in-1-9:
所有模型都需要在已安装的应用程序内定义或声明显式的 app_label。此外,在加载应用程序之前不可能导入它们。特别是,无法在应用程序的根包中导入模型。
通过将您的信号导入__init__.py
,您将间接导入应用程序的根包中的模型。避免这种情况的一种选择是更改sender
到一个字符串:
@receiver(pre_save, sender='<appname>.Comment')
def process_hashtags(sender, instance, **kwargs):
...
连接使用的信号的推荐方法@receiver
1.9 中的装饰器是创建一个应用程序配置 https://docs.djangoproject.com/en/1.9/ref/applications/#application-configuration,并导入信号模块AppConfig.ready()
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)