博客网站评论功能报错:请求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>
路由代码中的其他错误
- 表单取值调用错误:
request.form.get是方法,需用括号调用而非方括号:
错误代码:
text = request.form.get['text']
修复后:
text = request.form.get('text')
- Post查询语句错误:
filter_by需传入键值对,Post的主键是id,且需用.first()获取实际对象:
错误代码:
post = Post.query.filter_by(post_id)
修复后:
post = Post.query.filter_by(id=post_id).first()
- 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)
修复步骤总结
- 修正表单的action路径和input的name字段
- 修复路由里的表单取值、Post查询、Comment对象赋值代码
- 修正模型中的关系命名避免冲突
- 重启服务后测试评论提交功能
内容的提问来源于stack exchange,提问作者cashie_tech
相关产品推荐
相关产品推荐

