正在 url 模式文件中加载 django.apps 模块

Loading django.apps module inside the url patterns file

我已将路由器 属性(DRF 的 SimpleRouter 实例)添加到我的 AppConfig。我想在我的 urls.py 文件中获取所有已安装应用程序的列表,并将任何带有路由器 属性 的应用程序添加到我的 url 模式中。

这是我的 urls.py 文件:

from django.conf.urls import url, include
from django.contrib import admin
from django.apps import apps

urlpatterns = [
    url(r'^admin/', include(admin.site.urls))
]

# Loading the routers of the installed apps and core apps
for app in apps.get_app_configs():
    if hasattr(app, 'router'):
        urlpatterns += app.router.urls

这是我修改后的 AppConfig 的示例:

from django.apps import AppConfig
from .router import auth_router


class AuthConfig(AppConfig):

    name = "core.auth"
    # to avoid classing with the django auth
    label = "custom_auth"

    # router object
    router = auth_router

    def ready(self):
        from .signals import user_initialize, password_reset_set_token

default_app_config = 'core.auth.AuthConfig'

当我尝试上述解决方案时,我最终收到 "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet." 错误消息!

我已经尝试使用建议的解决方案 here 但其中 none 有效!

错误不是由 urls.py 文件夹引起的,而是由 AppConfig 引起的。我必须在 ready 方法

中导入 auth_router
from django.apps import AppConfig


class AuthConfig(AppConfig):

    name = "core.auth"
    # to avoid classing with the django auth
    label = "custom_auth"

    # router object
    router = None

    def ready(self):
        from .signals import user_initialize, password_reset_set_token
        from .router import auth_router
        self.router = auth_router

default_app_config = 'core.auth.AuthConfig'