提交表单时评论未写入数据库,终端报Broken pipe错误求助
问题分析与解决
1. 表单提交被提前中断(引发Broken pipe错误)
你的提交按钮添加了onClick="window.location.reload()",这会在表单发送POST请求前强制刷新页面,直接中断后端的处理流程,终端因此报Broken pipe错误,评论也可能因请求中断无法完成保存。
解决方法:删除按钮的onClick属性,让表单正常提交后通过后端重定向完成页面刷新:
<button class="btn btn-outline-secondary rounded-0 comment-button" id="form-submit" type="submit">Submit</button>
2. 评论显示的条件限制
HTML模板渲染评论时加入了{% if comment.status %}判断,如果你的Comment模型中status字段默认值不是True,新保存的评论就不会被展示。
解决方法:
- 要么在保存评论时主动设置状态为启用:
user_comment = comment_form.save(commit=False) user_comment.post = post user_comment.user = request.user user_comment.status = True # 新增此行,确保评论状态为显示 user_comment.save()
- 若不需要
status字段的过滤逻辑,直接删除模板中的{% if comment.status %}和对应的{% endif %}。
3. 重定向参数写法错误
后端redirect的参数格式有误,当前传入的字典{'slug': slug}不符合Django的重定向参数规范,正确写法应为关键字参数或位置参数:
# 关键字参数写法 return redirect('viewpost', slug=slug) # 或位置参数写法 return redirect('viewpost', args=[slug])
额外检查项
- 确认
Comment模型中post外键的related_name设置为comments,否则post.comments.all无法正确关联并获取评论。 - 检查数据库,确认评论是否已成功存入(解决上述问题后,评论应能正常写入数据库)。
内容的提问来源于stack exchange,提问作者David Henson
相关产品推荐
相关产品推荐

