我很难理解app_name和命名空间之间的联系。
考虑项目级别urls.py
from django.urls import path, include
urlpatterns = [
path('blog/', include('blog.urls', namespace='blog')),
]
考虑应用程序级别(博客)urls.py
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.post_list, name='post_list'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'),
]
如果我注释掉app_name,我会得到以下内容。
'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.
如果我将app_name重命名为某个任意字符串,我不会收到错误。
app_name = 'x'
我已阅读文档,但仍未点击。有人可以告诉我app_name和命名空间是如何/为什么连接的,为什么允许它们具有不同的字符串值?是不是手动设置app_name多余?
尝试删除app_name ='blog'
在你的情况下你应该使用:
'blog:post_list'
和
'blog:post_detail'
您也可以删除第一个网址中的namespace='blog'
,如下所示:
urlpatterns = [
path('blog/', include('blog.urls')),
]
然后在你的模板中你可以引用没有'blog:.....'的网址:
'post_list'
'post_detail'
尝试使用元组。
urlpatterns = [
path('blog/', include(('blog.urls', 'blog'))),
]