You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask删除评论跳转报werkzeug.routing.BuildError缺少post_id问题咨询

错误根因

你的post视图路由配置了必填路径参数<int:post_id>,删除评论后执行重定向时,调用url_for('post')没有传入该必填参数,导致Flask无法生成目标跳转URL,触发500内部服务错误。评论删除逻辑本身是正常执行的,所以返回上一页可以看到删除成功的提示和效果。

修复步骤
  1. 修改routes.py中delete_comment路由的重定向逻辑
    你可以直接从待删除的评论对象中获取关联的帖子ID,传给url_for方法:

    @app.route("/comment-delete/<int:comment_id>", methods=['POST'])
    @login_required
    def delete_comment(comment_id):
        comment = Comment.query.filter_by(id=comment_id).first()
        if comment.author != current_user:
            abort(403)
        db.session.delete(comment)
        db.session.commit()
        flash('Your comment has been deleted!', 'success')
        # 修改下面这行,传入必填的post_id参数
        return redirect(url_for('post', post_id=comment.post_id))
    
  2. 优化模板中多余参数传递(非强制,建议修改)
    delete_comment路由仅需要comment_id参数,模板表单中传递的post_id、post属于冗余参数,可以删除:

    <form action="{{url_for('delete_comment', comment_id=comment.id)}}" method="POST">
      <input class="btn btn-danger" type="submit" value="Delete">
    </form>
    

修改完成后重新运行服务即可,删除评论后会正常跳转回对应帖子详情页,不再触发500错误。


内容的提问来源于stack exchange,提问作者Earle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 04:54:03