今天在使用django做路由配置时,出现了一个关于include函数的问题,按照以往的经验,我在总路由里配置子路由时,写下了如下代码:
urlpatterns = [
path('',include('**.urls',namespace='子应用名'))
]
结果报出如下错误:
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.
意为我在申明命名空间是没有提供一个子应用名,不符合我之前的认知,于是我又去看了一下include函数的官方设计:
def include(arg, namespace=None):
app_name = None
if isinstance(arg, tuple):
# Callable returning a namespace hint.
try:
urlconf_module, app_name = arg
if isinstance(urlconf_module, str):
urlconf_module = import_module(urlconf_module)
patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module)
app_name = getattr(urlconf_module, 'app_name', app_name)
if namespace and not app_name:
raise ImproperlyConfigured(
'Specifying a namespace in include() without providing an app_name '
'is not supported. Set the app_name attribute in the included '
'module, or pass a 2-tuple containing the list of patterns and '
'app_name instead.',
首先include函数会先去判断首个输入参数的类型,正常我输入的是是子路由路径,也就是字符串,然后大致可以看出它尝试把字符串转化一个对象,然后获取路由和子应用名,当有命名空间,并且没有获取到了子应用名,就会提出今天我所说的异常,我作为一个懒人觉得太麻烦,明显上一张图的元组逻辑更为简单,偷懒的方法当然是把路径改写如下:
urlpatterns = [
path('',include(('**.urls','子应用名'),namespace='子应用名'))
]
成功跑动了,哈哈