关于django2.2版本的include函数的用法

今天在使用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='子应用名'))
]

成功跑动了,哈哈

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值