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

Flask点赞功能执行后异常跳转首页问题及解决方法

Flask蓝图点赞路由跳转异常问题

编辑补充:我已通过将变量名从post_id改为post_num解决了该问题,推测是参数传递过程中变量名相似导致了歧义错误。

相关代码

前端post.html模板代码

{% if current_user.is_authenticated %}
    {% if current_user.has_liked_post(post) %}
        <a href="{{ url_for('users.like_post', post_id=post.id, action='unlike') }}">Unlike</a>
    {% else %}
        <a href="{{ url_for('users.like_post', post_id=post.id, action='like') }}">Like</a>
    {% endif %}
{% endif %}

后端路由代码

注:posts和users均为已注册的蓝图

@users.route('/like/<int:post_id>/<action>')
@login_required
def like_post(post_id, action):
    this_id = post_id
    post = Post.query.filter_by(id=post_id).first_or_404()
    if action == 'like':
        current_user.like_post(post)
        db.session.commit()
    if action == 'unlike':
        current_user.unlike_post(post)
        db.session.commit()
    return redirect(url_for('posts.post', post_id=this_id))

@posts.route("/post/<int:post_id>")
def post(post_id):
    post = Post.query.get_or_404(post_id)
    print(post)
    return render_template('post.html', title=post.title, post=post)

异常现象

  • 点击点赞/取消点赞按钮时,点赞数据会正常写入数据库,手动返回帖子页后按钮状态会正确切换,但页面会自动跳转到网站首页
  • 点赞操作触发跳转时,@posts.post路由中的print(post)语句会正常执行,控制台能正确输出对应的帖子对象,说明路由参数传递、跳转逻辑本身运行正常,但最终没有渲染帖子详情页
  • 直接访问帖子详情页、其他功能中使用同语法跳转至帖子详情页均运行正常,不会出现跳转首页的问题
  • 已排查确认post.html及相关关联代码中没有指向首页的跳转逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 03:54:07