Flask删除评论跳转报werkzeug.routing.BuildError缺少post_id问题咨询
错误根因
你的post视图路由配置了必填路径参数<int:post_id>,删除评论后执行重定向时,调用url_for('post')没有传入该必填参数,导致Flask无法生成目标跳转URL,触发500内部服务错误。评论删除逻辑本身是正常执行的,所以返回上一页可以看到删除成功的提示和效果。
修复步骤
修改
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))优化模板中多余参数传递(非强制,建议修改)
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
相关产品推荐
相关产品推荐

