基于我正在阅读的Django文档,似乎app文件夹中的signals.py是一个很好的开始,但我面临的问题是,当我为pre_save创建信号时,我尝试从模型中导入类它与我模型中的导入冲突. # models.pyfrom djang
# models.py from django.contrib.auth.models import User from django.db import models from django.utils.translation import gettext as _ from signals import * class Comm_Queue(CommunicatorAbstract): queue_statuses = ( ('P', _('Pending')), ('S', _('Sent')), ('E', _('Error')), ('R', _('Rejected')), ) status = models.CharField(max_length=10, db_index=True, default='P') is_html = models.BooleanField(default=False) language = models.CharField(max_length=6, choices=settings.LANGUAGES) sender_email = models.EmailField() recipient_email = models.EmailField() subject = models.CharField(max_length=100) content = models.TextField()
# signals.py from django.conf import settings from django.db.models.signals import pre_save from django.dispatch import receiver from models import Comm_Queue @receiver(pre_save, sender=Comm_Queue) def get_sender_email_from_settings(sender, **kwargs): obj=kwargs['instance'] if not obj.sender_email: obj.sender_email='%s' % settings.ADMINS[0][1]
此代码将无法运行,因为我在signals.py中导入了Comm_Queue,我还导入了models.py中的信号.
任何人都可以就如何解决这个问题提出建议吗?
问候
原来的答案,对于Django< 1.7: 您可以通过在应用程序的__init__.py文件中导入signals.py来注册信号:# __init__.py import signals
这将允许从signals.py导入models.py而不会出现循环导入错误.
这种方法的一个问题是,如果你使用的是coverage.py,它会混淆覆盖率结果.
Related discussion
编辑:对于Django> = 1.7:
自从引入AppConfig以来,推荐的导入信号的方法是在init()函数中.有关详细信息,请参见Eric Marcos’ answer.