Django 2 命名空间和 app_name
Django 2 namespace and app_name
我很难理解 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'
我已阅读文档,但仍无法点击。有人能告诉我 how/why app_name 和命名空间是连接的吗?为什么允许它们有不同的字符串值?手动设置 app_name 不是多余的吗?
尝试删除 app_name='blog'
在你的情况下你应该使用:
'blog:post_list'
和
'blog:post_detail'
您也可以像这样删除第一个 url 中的 namespace='blog'
:
urlpatterns = [
path('blog/', include('blog.urls')),
]
然后在您的模板中您可以引用 url 而没有 'blog:.....':
'post_list'
'post_detail'
尝试使用元组。
urlpatterns = [
path('blog/', include(('blog.urls', 'blog'))),
]
我很难理解 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'
我已阅读文档,但仍无法点击。有人能告诉我 how/why app_name 和命名空间是连接的吗?为什么允许它们有不同的字符串值?手动设置 app_name 不是多余的吗?
尝试删除 app_name='blog'
在你的情况下你应该使用:
'blog:post_list'
和
'blog:post_detail'
您也可以像这样删除第一个 url 中的 namespace='blog'
:
urlpatterns = [
path('blog/', include('blog.urls')),
]
然后在您的模板中您可以引用 url 而没有 'blog:.....':
'post_list'
'post_detail'
尝试使用元组。
urlpatterns = [
path('blog/', include(('blog.urls', 'blog'))),
]