_uuuinit_uuuuu.py中的自定义函数导致尚未安装Django应用程序错误

2024-06-11 20:16:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有如下设置

    Tasks
      |__ __init__.py
      |__ a.py
      |__ b.py
      |__ c.py
         ...

在_uinit__u.py文件中

    from .a import custom1, custom2
    from .b import custom3, custom4

我在Tasks中编写了一个函数,要求将Tasks添加为已安装的应用程序

但是,自定义函数会引发django.core.exceptions.AppRegistryNotReady:“应用程序尚未加载。”

回溯会导致一个自定义函数尝试导入的点

from django.contrib.auth.models import User

为什么会发生这种情况?有没有一种方法可以在不将自定义函数移出_init__u;.py文件的情况下修复此错误


Tags: 文件django函数frompyimport应用程序init
1条回答
网友
1楼 · 发布于 2024-06-11 20:16:59

Django初始化的顺序是welldocumented

1.) First Django imports each item in INSTALLED_APPS.

At this stage, your code shouldn’t import any models!

3.)Finally Django runs the ready() method of each application configuration.

并且进一步作为{}中的{a2}

Subclasses can override this method to perform initialization tasks such as registering signals. It is called as soon as the registry is fully populated.

class RockNRollConfig(AppConfig):
# ...

    def ready(self):
        # importing model classes
        from .models import MyModel  # or...
        MyModel = self.get_model('MyModel')

        # registering signals with the model's string label
        pre_save.connect(receiver, sender='app_label.MyModel')

您可以考虑在函数内使用^{},用“{< CD3>} false

替换导入”

但我不确定它是否会根据您的用例工作

相关问题 更多 >