完成评论功能
- 定义评论的视图函数
@app.route('/comment/',methods=['POST'])
def comment():
读取前端页面数据,保存到数据库中 - 用<input type="hidden" 方法获取前端的"question_id"
- 显示评论次数
- 要求评论前登录
- 尝试实现详情页面下的评论列表显示
@app.route('/comments',methods=["POST"]) @login_first def comments(): comment = request.form.get("detail1") author_id = Question.query.filter(User.username == session.get('user')).first().id ques_id = request.form.get("question_id") comm = Comment(detail=comment, author_id=author_id,question_id=ques_id) db.session.add(comm) db.session.commit() return redirect(url_for('detail',question_id=ques_id))
<form action="{{ url_for("comments") }}" method="post"> <div> <textarea style="width: 400px" id="xiang" rows="5" name="detail1" placeholder="请输入您的评论"></textarea><br> <input style="display: none" value="{{ ques.id }}" name="question_id"/> <input type="submit" value="发送" style="width:45px;height:25px;font-size:15px"> </div> </form> <div> <h4 >评论:({{ ques.comment|length }})</h4>
<ul class="note">
{% for foo in ques.comment %}
<li class="lis">
<div class="author">
<a class="nickname" target="_blank" href="{{ url_for("detail",question_id=foo.id) }}">{{ foo.author.username }}说:</a>
<span class="time">{{ foo.create_time }}</span>
<p>{{ foo.detail }}</p>
</div>
</li>
{% endfor %}
</ul>