问题描述
基于我正在阅读的Django文档,看来app文件夹中的 signals.py
是一个很好的起点,但是我面临的问题是当我为 pre_save
创建信号并尝试从模型导入类时,它与模型中的 import
冲突
Based on Django's documentation I was reading, it seems like signals.py
in the app folder is a good place to start with, but the problem I'm facing is that when I create signals for pre_save
and I try to import the class from model it conflicts with the import
in my model.
# 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
,并且还在模型内导入了信号。 py
。
This code will not run because I import Comm_Queue
inside signals.py
and I also import the signals inside models.py
.
有人可以建议我如何解决这个问题吗?
Can anyone advice on how I could over come this issue?
致谢
推荐答案
Origi最终答案,对于Django< 1.7:
您可以通过在应用程序的 __ init__中导入
文件: signals.py
来注册信号.py
Original answer, for Django < 1.7:
You can register the signals by importing signals.py
in the app's __init__.py
file:
# __init__.py
import signals
这将允许从<$ c $导入 models.py
c> signals.py 没有循环导入错误。
This will allow to import models.py
from signals.py
without circular import errors.
这种方法的一个问题是,如果您使用的是覆盖范围结果coverage.py。
One problem with this approach is that it messes up the coverage results if you're using coverage.py.
自AppConfig起引入后,建议的导入信号的方法是在其 init()
函数中。有关更多详细信息,请参见。
Since AppConfig was introduced, the recommended way of importing signals is in its init()
function. See Eric Marcos' answer for more details.
这篇关于将我的signals.py文件保留在Django项目中的正确位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!