Django2.0异常:Specifying a namespace in include() without providing an app_name is not supported.

主目录下的urls.py如下:

1
2
3
4
5
6
7
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
path(r'admin/', admin.site.urls),
path(r'',include('learning_logs.urls',namespace='learning_logs'),
]

但是报错了!

‘Specifying a namespace in include() without providing an app_name ‘
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源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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)

注:isinstance是Python中的一个内建函数。是用来判断一个对象的变量类型。第一个isinstance判断arg是不是个元组,又有这个 urlconf_module, app_name = arg,由此说明include(arg,namespace=''),arg是个元组

所以更改后的代码应该为:

1
2
3
4
urlpatterns = [
path(r'admin/', admin.site.urls),
path(r'',include(('learning_logs.urls','learning_logs'),namespace='learning_logs')),
]

撒花完结!