我很难理解 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')),
]
然后在您的模板中,您可以引用没有“博客:.....”的网址:
'post_list'
'post_detail'
