Django报错NoReverseMatch:newreply路由空参数匹配失败
报错根因
触发NoReverseMatch的核心原因是newreply视图渲染模板时未向模板上下文传递post对象:
- 视图中虽然提前查询了对应帖子
post = Post.objects.get(id=post_id),但构造模板上下文时仅传入了form,没有将post加入上下文 - 模板中
{% url 'board:newreply' post.id %}反向解析路由时,获取不到post变量,post.id被解析为空字符串,相当于传入了空值作为路由参数,和路由规则要求post_id必须为数字的匹配规则冲突,因此抛出参数不匹配的反向解析错误。
另外你贴出的代码存在两处会触发其他报错的疏漏:
urls.py中urlpatterns列表末尾缺少闭合方括号]- 模板中form标签的
action属性闭合引号后直接拼接method,缺少空格,会导致HTML属性解析异常
修复方法
按以下顺序修改代码即可解决问题:
- 修改newreply视图的上下文构造逻辑,将查询到的post对象传入模板,修正后的完整视图代码:
from django.shortcuts import render, redirect, get_object_or_404 from .models import Post from .forms import ReplyForm def newreply(request, post_id): post = get_object_or_404(Post, id=post_id) # 替换原有get写法,避免帖子不存在时抛出500错误 if request.method != "POST": form = ReplyForm() else: form = ReplyForm(data=request.POST) if form.is_valid(): newreply = form.save(commit=False) newreply.post = post newreply.save() return redirect('board:detail', post_id=post.id) # 提交后跳转到对应帖子详情页,使用体验更好 # 上下文补充传入post对象 context = {'form': form, 'post': post} return render(request, 'board/newreply.html', context)
- 补全
urls.py中urlpatterns的闭合方括号,修正后的路由配置:
from django.urls import path from . import views app_name = 'board' urlpatterns = [ path('', views.index, name='index'), path('<int:post_id>/', views.postdetail, name='detail'), path('newmsg/', views.newmsg, name='newmsg'), path('newreply/<int:post_id>/', views.newreply, name='newreply') ] # 补全此处的闭合方括号
- 修正模板中form标签的属性空格问题,模板核心代码如下:
{% extends 'pages/base.html' %} {% block content %} <p>Add your reply here</p> <!-- 补全action和method之间的空格 --> <form action="{% url 'board:newreply' post.id %}" method="post"> {% csrf_token %} {{ form.as_p }} <button name="submit">Add post</button> </form> {% endblock content %}
修改完成后重启Django服务,访问对应回复路径即可正常加载页面,不会再出现NoReverseMatch错误。
内容的提问来源于stack exchange,提问作者Pandammonia
相关产品推荐
相关产品推荐

