Django页面出现No reverse match错误,评论表单无法正常显示求助
问题分析与修复方案
核心问题
触发"No reverse match"错误的原因集中在以下几点:
模板变量未定义 + 查询结果类型错误
视图single_blog中用News.objects.filter(pk=pk)返回的是QuerySet集合,而非单个新闻对象,且context里没有new_pk变量,模板中{% url 'save_comment' new_pk %}找不到对应值,导致反向解析失败。视图参数与URL配置不匹配
save_comment视图定义了pk和new_pk两个参数,但urls中只配置了一个<int:pk>参数,反向解析时参数数量不匹配,无法匹配对应路由。表单提交方式错误
表单未指定method="POST",默认GET请求会暴露表单数据,还会触发CSRF验证失败,不符合表单提交规范。模型外键赋值错误
Comments模型的外键是post,但视图里用form.instance.new_id赋值,字段名不匹配,导致数据无法正确关联到对应新闻。
修正后的代码
views.py
from django.shortcuts import render, get_object_or_404, redirect from .models import News, Comments from .forms import CommentForm def single_blog(request, pk): # 获取单个新闻对象,不存在则返回404 news = get_object_or_404(News, pk=pk) comment_form = CommentForm() context = { 'title': 'Новость', 'news': news, 'comment_form': comment_form } return render(request, 'blog/single-blog.html', context) def save_comment(request, pk): # 仅接收新闻的pk参数 if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): # 关联到对应新闻,使用正确的外键字段名 form.instance.post_id = pk comment = form.save() return redirect('single-blog', pk=pk) # 非POST请求直接返回详情页 return redirect('single-blog', pk=pk)
urls.py
from django.urls import path from . import views urlpatterns = [ path('single-blog/<int:pk>', views.single_blog, name='single-blog'), # 配置单个pk参数,与视图参数匹配 path('save_comment/<int:pk>', views.save_comment, name='save_comment') ]
HTML模板
<h4>发表回复</h4> <!-- 指定POST方法,使用context中news对象的pk --> <form class="form-contact comment_form" action="{% url 'save_comment' news.pk %}" id="commentForm" method="POST"> {% csrf_token %} <div class="row"> <div class="col-sm-6"> <div class="form-group"> {{ comment_form.author }} </div> </div> <div class="col-12"> <div class="form-group"> {{ comment_form.text }} </div> </div> </div> <!-- 添加提交按钮 --> <button type="submit" class="btn btn-primary">提交评论</button> </form>
内容的提问来源于stack exchange,提问作者Shaxriyor
相关产品推荐
相关产品推荐

