找不到页面(404) - 没有帖子匹配给定的查询

时间:2016-04-05 14:22:45

标签: django django-urls

我正在Django博客上工作,并为帖子标题实施了slug我偶然发现了一个问题。
错误是

  

找不到页面(404)
  请求方法:GET
  请求网址:http://localhost:8000/post/new/
  提出者:blog.views.post_detail

  没有帖子匹配给定的查询。

这是我的 urls.py

from django.conf.urls import include, url
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^$', views.post_list),
    url(r'^register', views.register),
    url(r'^activate/(?P<activation_key>\w+)/', views.register_confirm),
    url(r'^email_check', views.email_check),
    url(r'^password_check', views.password_check),
    url(r'^login', views.login),
    url(r'^edit/$', views.update_profile),
    url(r'^post/(?P<slug>[-_\w]+)/$', views.post_detail),
    url(r'^post/new/$', views.post_new, name='post_new'),
    url(r'^post/(?P<slug>[-_\w]+)/edit/$', views.post_edit, name='post_edit'),
    url(r'^drafts/$', views.post_draft_list, name='post_draft_list'),
    url(r'^post/(?P<slug>[-_\w]+)/publish/$', views.post_publish, name='post_publish'),
    url(r'^post/(?P<slug>[-_\w]+)/remove/$', views.post_remove, name='post_remove'),
    url(r'^post/(?P<slug>[-_\w]+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'),
    url(r'^comment/(?P<slug>[-_\w]+)/approve/$', views.comment_approve, name='comment_approve'),
    url(r'^comment/(?P<slug>[-_\w]+)/remove/$', views.comment_remove, name='comment_remove'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

view.py 文件

@login_required
def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save()
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('blog.views.post_detail', slug=post.slug)
    else:
        form = PostForm()
    return render(request, 'blog/post_new.html', {'form': form})

它说错误是由&#34; post_detail&#34;引起的,所以这里是

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

我错过了什么?

1 个答案:

答案 0 :(得分:5)

这种情况正在发生,因为new与正则表达式[-_\w]+匹配。

您必须重新订购网址模式中的网址条目

改变这个:

url(r'^post/(?P<slug>[-_\w]+)/$', views.post_detail),
url(r'^post/new/$', views.post_new, name='post_new'),

有了这个:

url(r'^post/new/$', views.post_new, name='post_new'),
url(r'^post/(?P<slug>[-_\w]+)/$', views.post_detail),

解释

代码中的post_detail url条目在post_new url之前进行评估。这比post_detail优先post_new

由于post_detail网址为/post/ + 匹配 [-_\w]+new匹配正则表达式,Django认为您正在传递{{ 1}}作为new slug视图,并将其作为关键字参数传递给视图。由于没有post_detail作为slug的帖子,视图会返回new

404 Not found高于post_new时,post_detail指向/post/new/视图,post_new +任何正则表达式匹配点指向/post/。< / p>