gpt4 book ai didi

python - Django pre_delete 信号被忽略

转载 作者:太空宇宙 更新时间:2023-11-03 15:04:00 25 4
gpt4 key购买 nike

这是在模型文档的 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)

那么问题是什么?我应该在那里导入更多东西吗?或者我应该将此文件导入某处吗?

最佳答案

问题是,如果您将它放在 signals.py 中(按照推荐)但什么都不做,那么没有人会导入该文件。

你应该关注this advice , 特别是

In practice, signal handlers are usually defined in a signals submodule of the application they relate to. Signal receivers are connected in the ready() method of your application configuration class. If you’re using the receiver() decorator, simply import the signals submodule inside ready().

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


完整的过程应该是:

# my_app/__init__.py

default_app_config = 'my_app.apps.ConfigForMyApp'

apps.py 应该是:

# my_app/apps.py

from django.apps import AppConfig

class ConfigForMyApp(AppConfig):
# Optionally add `name` and `verbose_name`
# for the app
def ready(self): # overriding the ready method
# This will trigger the @receiver decorator
# and thus connect the signals
import my_app.signals

关于python - Django pre_delete 信号被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34948102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com