在include()中指定命名空间而不提供app_name

时间:2018-01-29 05:29:54

标签: django django-urls

models.py

from django.conf.urls import include, url

app_name = "Review"

urlpatterns = [
  url(r'^books/', include("Review.urls", namespace='reviews')),
]

评分\ urls.py

from django.conf.urls import include, url
from django.contrib import admin
from .views import (
  ReviewUpdate,
  ReviewDelete,
)

urlpatterns = [
  url(r'^reviews/(?P<pk>\d+)/edit/$', ReviewUpdate.as_view(), name='review_update'),
  url(r'^reviews/(?P<pk>\d+)/delete/$', ReviewDelete.as_view(), name='review_delete'),
]

我在urlpatterns之前提供app_name。但它在运行我的代码时给了我错误。错误如下:

  File "E:\workspace\python\web\Book_Review_App\Book\urls.py", line 13, in <module>
    url(r'^books/', include("Review.urls", namespace='reviews')),
  File "E:\workspace\python\web\Book_Review_App\venv\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.

请帮忙。

1 个答案:

答案 0 :(得分:6)

需要在app的urls.py中设置app_name,而不是主urls.py。

在review.urls.py中添加以下内容,

from django.conf.urls import include, url 
from django.contrib import admin 
from .views import ( ReviewUpdate, ReviewDelete, )

app_name = 'Review'

urlpatterns = [ 
    url(r'^reviews/(?P<pk>\d+)/edit/$', ReviewUpdate.as_view(), name='review_update'),
    url(r'^reviews/(?P<pk>\d+)/delete/$', ReviewDelete.as_view(), name='review_delete'),
]

并从主网址

中删除app_name

编辑:对于op在评论中提到的管理问题, 在主urls.py

from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]