urls urls中使用 1 urlpatterns = [ 2 path('admin/', admin.site.urls), 3 path('polls/', include('polls.urls', namespace='polls')), 4 ] View Code 運行後報錯,錯誤代碼 ...
urls
urls中使用
1 urlpatterns = [ 2 path('admin/', admin.site.urls), 3 path('polls/', include('polls.urls', namespace='polls')), 4 ]View Code
運行後報錯,錯誤代碼如下:
1 django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name att 2 ribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.Error Code
根據報錯,我們可知,需要提供一個app_name,我們來看源碼
def include(arg, namespace=None): app_name = None if isinstance(arg, tuple): # Callable returning a namespace hint. try: urlconf_module, app_name = arg # 從此處可以看出,需要提供一個二元元組,二元元組第二個參數需要提供app_name這個名稱 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)
從第六行可以看出,需要提供一個二元元組,二元元組第二個參數需要提供app_name這個名稱。因此,
方法一:修改urls.py為
urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include(('polls.urls', 'polls'), namespace='polls')), ]
方法二:在[app_name]目錄下的urls.py中的urlpatterns前面加上app_name='[app_name]'
from django.urls import path from polls import views app_name = 'polls' urlpatterns = [ path('', views.index, name="index"), path('<int:question_id>/', views.details, name="details"), path('<int:question_id>/results/', views.results, name="results"), path('<int:question_id>/vote/', views.vote, name="vote"), ]