如何在Django中修复此NoReverseMatch?

时间:2017-06-14 19:18:29

标签: python django

编辑:这个问题与django 1.8 NoReverseMatch at error不同,因为这个问题专门询问如何使用ModelViewSet类

我试图制作博客文章/脸谱墙式应用程序,并在Django中获得NoReverseMatch错误。它在尝试提交帖子后发生。

这是我的views.py

from django.shortcuts import render, get_object_or_404, redirect
from wall.models import Post
from .forms import PostForm

def index(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm()

    return render(request, 'wall/index.html', {'form': form})

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

urls.py

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

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^post_detail/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]

post_detail.html

{% extends 'blog/base.html' %}

{% block content %}
    <div class="post">
        {% if post.published_date %}
            <div class="date">
                {{ post.published_date }}
            </div>
        {% endif %}
        <p>{{ post.text|linebreaksbr }}</p>
    </div>
{% endblock %}

错误页面显示

Reverse for 'post_detail' with keyword arguments '{'pk': 5}' not found
1 pattern(s) tried: ['$post_detail/(?P<pk>\\d+)/$']

我已经查看了this answer,但这些建议都没有帮助。我的正则表达式和网址名称拼写正确。

如何解决此错误?

这是我的基础urls.py

from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views as auth_views
from . import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', include('wall.urls'), name='index'),
    url(r'^accounts/register/$', views.register, name='register'),
    url(r'^accounts/register/complete/$', views.registration_complete, name='registration_complete'),
    url(r'^accounts/login/$', auth_views.login, name='login'),
    url(r'^accounts/logout/$', auth_views.logout, name='logout'),
    url(r'^accounts/loggedin/$', views.logged_in, name='loggedin'),
]

2 个答案:

答案 0 :(得分:1)

我认为您的问题是在表单提交后重定向,更改

return redirect('post_detail', pk=post.pk)

return redirect(reverse('post_detail', kwargs={'pk': post.pk}))

(导入反向使用:from django.core.urlresolvers import reverse

正如Alasdair指出的那样,你的基础urls.py中也缺少$包含内容。

答案 1 :(得分:1)

当您包含应用的网址时,您的正则表达式中看起来好像有一美元。去掉它。