我已经在我的AppConfig中添加了一个路由器属性(DRF的SimpleRouter实例)。我想在我的urls.py文件中获取所有已安装应用的列表,并将任何带有路由器属性的应用添加到我的网址模式中。
这是我的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:尚未加载应用程序”。错误信息!
我已尝试使用提议的解决方案here但其中没有一个有效!
答案 0 :(得分:1)
该错误不是由urls.py文件夹引起的,而是由AppConfig引起的。我必须在ready方法
中导入auth_routerfrom 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'