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

Flask帖子删除权限异常:正确用户仍无法删除帖子

Flask帖子删除权限问题修复方案

核心问题

删除路由的权限判断逻辑错误:你将当前用户ID与帖子ID做对比(current_user.id != post.id),但实际应该对比用户ID和帖子的作者ID(post.author),这就是作者点击删除仍提示权限不足的原因。

修正后的删除路由代码

@views.route("/delete-post/<id>")
@login_required
def delete_post(id):
    post = Post.query.filter_by(id=id).first()

    if not post:
        flash("Post does not exist.", category='error')
    # 修正判断条件:对比当前用户ID与帖子的author字段
    elif current_user.id != post.author:
        flash('You do not have permission to delete this post.', category='error')
    else:
        db.session.delete(post)
        db.session.commit()
        flash('Post deleted.', category='success')

    return redirect(url_for('views.home'))

额外验证点

  • 模板中的权限判断{% if user.id == post.author %}逻辑正确,和修复后的后端判断保持一致,因此删除按钮的显示逻辑无需修改。
  • 确认@login_required装饰器正常生效,current_user能正确获取当前登录用户对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:28:33