Django pre_delete 信号被忽略

Rob*_*rax 5 python django django-signals

这是在模型文档的 pre_delete 上运行的内容。当按照建议的最佳实践放入单独的文件 (signals.py) 时,此代码会被完全忽略。当放入模型文件时,它工作正常。

from django.db.models.signals import pre_delete, pre_save
from django.dispatch import receiver
from _myTools.functions import ImageProcessing
from content_image.models import Document
import os

# Image deletion when deleting entire entry
@receiver(pre_delete, sender=Document, dispatch_uid='document_delete_signal')
def entry_deletion_images_delete(sender, instance, using, **kwargs):
    for key, value in instance.imageSizes.items():
        name_of_image_field = str(getattr(instance, key))  # Converts to string, if not is object itself
        os.remove(instance.baseDir + name_of_image_field)
        setattr(instance, key, None)
Run Code Online (Sandbox Code Playgroud)

那么问题出在哪里呢?我应该在那里导入更多东西吗?或者我应该在某处导入这个文件?

Mar*_*ram 4

问题是,如果您将其放入signals.py(按照建议)但不执行任何其他操作,那么没有人会导入该文件。

\n\n

您应该遵循此建议,尤其是

\n\n
\n

在实践中,信号处理程序通常在与其相关的应用程序的信号子模块中定义。信号接收器在应用程序配置类的 read() 方法中连接。如果您\xe2\x80\x99使用receiver()装饰器,只需在ready()内部导入信号子模块即可。

\n
\n\n

负责ready()导入模块,从而引发信号“连接”并允许信号接收器工作。

\n\n
\n\n

完整的程序应该是:

\n\n
# my_app/__init__.py\n\ndefault_app_config = \'my_app.apps.ConfigForMyApp\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

apps.py 应该是:

\n\n
# my_app/apps.py\n\nfrom django.apps import AppConfig\n\nclass ConfigForMyApp(AppConfig):\n    # Optionally add `name` and `verbose_name`\n    # for the app\n    def ready(self): # overriding the ready method\n        # This will trigger the @receiver decorator \n        # and thus connect the signals\n        import my_app.signals\n
Run Code Online (Sandbox Code Playgroud)\n