gpt4 book ai didi

python - django.core.exceptions.AppRegistryNotReady : Apps aren't loaded yet. 文件初始化

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

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

添加时出现异常:

  1. 导入信号init.py 文件(apps/application/init.py)

  2. 从模型导入审核在 signals.py 文件中 (apps/application/signals.py)

当模型 Review 中有插入时,我想发送一个 http 请求。

所以我需要导入Review模型(在__init.py__文件中)来执行下面的代码:

@receiver (pre_save, sender = Review)
def my_handler (sender, ** kwargs):
....

最佳答案

在 Django 的 source 中,这是异常的来源:

def check_apps_ready(self):
"""Raise an exception if all apps haven't been imported yet."""
if not self.apps_ready:
raise AppRegistryNotReady("Apps aren't loaded yet.")

如您所见,请确保每个应用程序都就绪(已加载)。一般来说,当它与信号相关时,通常有两种情况。

  • 循环导入

    确保您的项目中没有。这可能会导致错误。

  • 在应用加载前注册信号

    参见 this了解更多信息。但是,帮助我理解 Django 在幕后如何工作的一件事是以下声明:

It is important to understand that a Django application is just a set of code that interacts with various parts of the framework. There’s no such thing as an Application object. However, there’s a few places where Django needs to interact with installed applications, mainly for configuration and also for introspection. That’s why the application registry maintains metadata in an AppConfig instance for each installed application.

因此,您可以做的是覆盖名为 AppConfig.ready()AppConfig 方法之一。它允许您执行初始化任务,例如注册信号。

# yourApp/__init__.py

default_app_config = 'yourappname.apps.YourAppConfig'

# yourApp/apps.py
from django.apps import AppConfig

class YourAppConfig(AppConfig):
name = 'yourappname'

def ready(self):
from yourappname import signals

更多信息

为了便于解释,这是从 Django 1.7+ 开始推荐的做法,这很可能是您的情况。其背后的逻辑是 application registry保留一个 bool 值 ready,仅在注册表完全填充并且所有 AppConfig.ready() 方法都被设置为 True叫了。

关于python - django.core.exceptions.AppRegistryNotReady : Apps aren't loaded yet. 文件初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51081783/

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