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

博客网站评论功能报错:请求URL未找到,求技术排查

博客评论功能404错误排查与修复方案

核心问题:路由与表单Action不匹配(404直接诱因)

路由定义的是/create-comment/<post_id>,但表单的action写的是/create_comment,既不匹配路由的连字符格式,也没传递必需的post_id参数,服务器找不到对应路由就会返回404。

修复表单代码:
用url_for动态生成路由并传递post_id,同时修正input的name字段与路由取值对应:

<form class="input-group mb-3" method="POST" action="{{ url_for('posts.create_comment', post_id=post.id) }}">
    <input type="text" id="text" class="form-control" placeholder="Comment" name="text">
    <div class="input-group-append">
      <button type="submit" class="btn btn-outline-secondary">Post</button>
    </div>
</form>

路由代码中的其他错误

  1. 表单取值调用错误:
    request.form.get是方法,需用括号调用而非方括号:
    错误代码:
text = request.form.get['text']

修复后:

text = request.form.get('text')
  1. Post查询语句错误:
    filter_by需传入键值对,Post的主键是id,且需用.first()获取实际对象:
    错误代码:
post = Post.query.filter_by(post_id)

修复后:

post = Post.query.filter_by(id=post_id).first()
  1. Comment对象赋值错误:
    Comment模型的字段是content,不是text:
    错误代码:
comment = Comment(text=text, post_id=post_id, author=current_user)

修复后:

comment = Comment(content=text, post_id=post_id, author=current_user)

模型代码中的关系命名冲突

User和Post模型里的关系名用了首字母大写的Comment,会与Comment类名冲突,改为小写复数:
User模型修复:

class User(db.Model, UserMixin):
    # 其他字段不变
    comments = db.relationship('Comment', backref='author', lazy=True)

Post模型修复:

class Post(db.Model):
    # 其他字段不变
    comments = db.relationship('Comment', backref='post', lazy=True)

修复步骤总结

  1. 修正表单的action路径和input的name字段
  2. 修复路由里的表单取值、Post查询、Comment对象赋值代码
  3. 修正模型中的关系命名避免冲突
  4. 重启服务后测试评论提交功能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:16:10