栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于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='子应用名'))
]

成功跑动了,哈哈

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/326162.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号