Django中redirect跳转PostDetail视图出现NoReverseMatch错误求助
解决NoReverseMatch错误:重定向到PostDetail视图失败
出现Reverse for 'PostDetail' not found错误,核心原因是Django找不到你指定名称的URL模式,或者参数传递有误。按以下步骤排查:
1. 确认URL配置的name参数正确
打开你的website/urls.py,找到PostDetail视图对应的URL规则,必须设置正确的name属性,且名称要和redirect里的字符串完全匹配(大小写敏感):
# website/urls.py示例 from django.urls import path from .views import PostDetail, createComment urlpatterns = [ path('posts/<int:pk>/', PostDetail.as_view(), name='PostDetail'), # 这里的name必须是'PostDetail' path('posts/<int:post_id>/comment/', createComment, name='create_comment'), ]
如果你的URL名称是小写的post_detail,那redirect里也要改成return redirect('post_detail', newComment.post.id)。
2. 修正redirect的参数传递方式
Django的redirect函数对于带参数的URL,建议用关键字参数传递,避免位置参数可能引发的匹配错误。假设你的PostDetail URL接受pk参数(比如<int:pk>),修改代码:
# website/views.py中createComment视图的重定向代码 return redirect('PostDetail', pk=newComment.post.id)
如果你的URL参数名是post_id(比如<int:post_id>),则改成:
return redirect('PostDetail', post_id=newComment.post.id)
3. 确保主项目urls.py包含app的URL配置
检查项目根目录的urls.py,确认已经引入了website的URL规则:
# 项目根urls.py示例 from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('website.urls')), # 必须包含这一行,否则找不到app里的URL ]
4. 验证帖子详情页能加载新评论
确保PostDetail视图已经把该帖子的评论查询出来,传给post_details.html模板:
# website/views.py的PostDetail视图示例 from django.views.generic import DetailView from .models import Post, Comment class PostDetail(DetailView): model = Post template_name = 'website/post_details.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # 查询当前帖子的所有评论,按时间排序 context['comments'] = Comment.objects.filter(post=self.object).order_by('-created_at') return context
然后在post_details.html里遍历渲染评论:
<!-- post_details.html示例 --> <h3>评论</h3> {% for comment in comments %} <div class="comment"> <p>{{ comment.content }}</p> <small>{{ comment.created_at }}</small> </div> {% endfor %}
按以上步骤调整后,提交评论就能正确重定向到帖子详情页,并且看到新增的评论了。
内容的提问来源于stack exchange,提问作者Lucia Quintas
相关产品推荐
相关产品推荐

