This question already has an answer here:
Unexpected NoReverseMatch error when using include() in urls patterns
                                
                                    (1个答案)
                                
                        
                                2年前关闭。
            
                    
编辑:此问题与django 1.8 NoReverseMatch at error不同,因为此问题专门询问如何使用ModelViewSet类

我正在尝试制作博客文章/ facebook墙式应用程序,并且在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,但是所有建议都没有帮助。我的正则表达式和url名称拼写正确。

如何解决此错误?

这是我的基本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'),
]

最佳答案

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

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中也没有包含一个$

关于python - 如何在Django中修复此NoReverseMatch? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44553000/

10-10 18:20
查看更多