知识网2021年11月14日 11:23原创
学习了namespace的用法之后,在url后面加上了namespace,启动服务突然抛出Specifying a namespace in include() without providing an app_name is not supported.异常,我的代码如下:
urlpatterns = [ # path('admin/', admin.site.urls), # path('', include(('shenghuo.urls','shenghuo'),namespace='shenghuo')), url('^admin/',admin.site.urls), url('^$',include('shenghuo.urls',namespace='shenghuo')) ]
具体的错误为:
File &/Library/Python/3.9/lib/python/site-packages/django/urls/conf.py&, line 38, in include
raise ImproperlyConfigured(
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.
我们可以看到是conf.py抛出的异常,conf.py源码如下:
def include(arg, namespace=None): app_name = None if isinstance(arg, tuple): # Callable returning a namespace hint. try: urlconf_module, app_name = arg except ValueError: if namespace: raise ImproperlyConfigured( 'Cannot override the namespace for a dynamic module that ' 'provides a namespace.' ) raise ImproperlyConfigured( 'Passing a %d-tuple to include() is not supported. Pass a ' '2-tuple containing the list of patterns and app_name, and ' 'provide the namespace argument to include() instead.' % len(arg) ) else: # No namespace hint - use manually provided namespace. urlconf_module = 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.', ) namespace = namespace or app_name # Make sure the patterns can be iterated through (without this, some # testcases will break). if isinstance(patterns, (list, tuple)): for url_pattern in patterns: pattern = getattr(url_pattern, 'pattern', None) if isinstance(pattern, LocalePrefixPattern): raise ImproperlyConfigured( 'Using i18n_patterns in an included URLconf is not allowed.' ) return (urlconf_module, app_name, namespace)
从include()函数可以看出来,这个函数有两个参数,一个arg,一个namespace,我在代码中也是两个参数,但是异常中提示了,没有提供app_name,还提示需要传入一个两元元组,从第六行代码:
urlconf_module, app_name = arg
可以看出来,arg就是那个元组,且给app_name赋值了,所以我们这里修改代码为:
urlpatterns = [ # path('admin/', admin.site.urls), # path('', include(('shenghuo.urls','shenghuo'),namespace='shenghuo')), url('^admin/',admin.site.urls), url('^$',include(('shenghuo.urls','null'),namespace='shenghuos')), ]
app_name可以随便定义,但是一定要有有值,直至问题解决。
注意:django3.0之后建议使用path的方式进行url的配置,而且工程中的settings.py默认使用path的方式了。
本文章网址:https://www.shsongjiang.com/p57/
很赞哦!(17)