'Specifying a namespace in include() without providing an app_name'

匿名 (未验证) 提交于 2019-12-03 08:35:02

问题:

Hi there just trying out django and I have the following urls files respectively. However, when I run the server and try to browse;

I get this error.

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\conf.py", line 39, in include     '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. 

project/urls.py

from django.conf.urls import include, url from django.contrib import admin  urlpatterns = [     url(r'^reviews/', include('reviews.urls', namespace='reviews')),     url(r'^admin/', include(admin.site.urls)), ] 

app/urls.py

from django.conf.urls import url  from . import views  urlpatterns = [     # ex: /     url(r'^$', views.review_list, name='review_list'),     # ex: /review/5/     url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'),     # ex: /wine/     url(r'^wine$', views.wine_list, name='wine_list'),     # ex: /wine/5/     url(r'^wine/(?P<wine_id>[0-9]+)/$', views.wine_detail, name='wine_detail'), ] 

What could be doing wrong?

回答1:

Check the docs for include here.

What you've done is not an acceptable way of passing parameters to include. You could do:

url(r'^reviews/', include(('reviews.urls', 'reviews'), namespace='reviews')), 


回答2:

Django 1.11+, 2.0+

You should set the app_name in the urls file you are including

Then you can include it the way you are doing it.

Also, it might be worth noting what Django docs say here https://docs.djangoproject.com/en/1.11/ref/urls/#include :

Deprecated since version 1.9: Support for the app_name argument is deprecated and will be removed in Django 2.0. Specify the app_name as explained in URL namespaces and included URLconfs instead.

( https://docs.djangoproject.com/en/1.11/topics/http/urls/#namespaces-and-include )



回答3:

Django 2.0 you should specify app_name in your urls.py, is not necessary to specify app_name argument on include.

Main Url file.

from django.contrib import admin from django.urls import path, include  urlpatterns = [     path('', include('apps.main.urls', namespace="main_app")),     path('admin/', admin.site.urls), ] 

Included Url.

from django.urls import path from . import views  app_name = 'main'  urlpatterns = [     path('', views.index, name='index'), ] 

Then use use in template as

<a href="{% url main_app:index' %}"> link </a> 

More details: https://code.djangoproject.com/ticket/28691



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!