2016-08-03 14 views
0

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

这是我的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但他们都没有工作!

回答

1

该错误不是由urls.py文件夹引起的,而是由AppConfig引起的。我必须在准备好的方法内导入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'