【问题标题】:NoReverseMatch at /blog/ Django 2.0.5/blog/ Django 2.0.5 中的 NoReverseMatch
【发布时间】:2018-06-07 14:37:19
【问题描述】:

我正在关注 Django 教程。由于不同的 Django 版本,我遇到了这个问题,我无法弄清楚。提前致谢

NoReverseMatch at /blog/
'blog' is not a registered namespace
Request Method: GET
Request URL:    http://127.0.0.1:8000/blog/
Django Version: 2.0.5
Exception Type: NoReverseMatch
Exception Value:    
'blog' is not a registered namespace
Exception Location: /Users/sumeixu/anaconda3/lib/python3.6/site-packages/django/urls/base.py in reverse, line 84
Python Executable:  /Users/sumeixu/anaconda3/bin/python
Python Version: 3.6.3
Python Path:    
['/Users/sumeixu/djangotest',
 '/Users/sumeixu/anaconda3/lib/python36.zip',
 '/Users/sumeixu/anaconda3/lib/python3.6',
 '/Users/sumeixu/anaconda3/lib/python3.6/lib-dynload',
 '/Users/sumeixu/anaconda3/lib/python3.6/site-packages',
 '/Users/sumeixu/anaconda3/lib/python3.6/site-packages/aeosa']
Server time:    Thu, 7 Jun 2018 14:32:43 +0000

博客/urls.py:

from django.conf.urls import url
from django.urls import path
from . import views

urlpatterns =[
    path('', views.list_of_post,name='list_of_post'),
    path('<slug:slug>/', views.list_of_post,name='post_detail')
]

urls.py

from django.contrib import admin
from django.urls import path,include

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

views.py

def post_detail(request,slug):
    post = get_object_or_404(Post,slug=slug)
    template = 'blog/post/post_detail.html'
    return render(request,template,{'post':post})

【问题讨论】:

    标签: python django


    【解决方案1】:

    include 中删除namespace/name

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

    然后在blog/urls.py中设置app_name

    app_name = 'blog'
    
    urlpatterns =[
        path('', views.list_of_post,name='list_of_post'),
        path('<slug:slug>/', views.list_of_post,name='post_detail')
    ]
    

    您可以在Django 1.9 release notes 中阅读有关此更改的更多信息。从 Django 2.0 开始,您不能在 include 中设置 namespace,除非设置了 app_name

    【讨论】:

    • 成功了。但是新的问题出现了。不知道如何解决? list_of_post() 得到了一个意外的关键字参数“slug”。 ://
    • 如果您仍然卡住,请提出一个新问题。这是一个不相关的问题,因此 cmets 不是解决问题的最佳场所。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 2017-11-26
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    相关资源
    最近更新 更多