作业32——完成评论功能

    1. 定义评论的视图函数
      @app.route('/comment/',methods=['POST'])
      def comment():
      读取页面数据,保存到数据库中。
@app.route('/comment/', methods=['POST'])
@loginFrist
def comment():
    comment_detail = request.form.get('new_comment')
    quest_id = request.form.get('question_id')
    author_id = User.query.filter(User.username == session.get('user')).first().id
    comment = Comment(detail=comment_detail, author_id=author_id, question_id=quest_id, )
    db.session.add(comment)
    db.session.commit()
    return redirect(url_for('detail', question_id=quest_id))
    1. 用<input type="hidden" 方法获取前端的"question_id" 

detail.html

<form role="form" action="{{ url_for('comment') }}" method="post">
                <div class="form-group">
                    <label for="exampleInputEmail1">Write down your answer~~</label>
                    <textarea class="form-control" id="exampleInputEmail1" name="new_comment"></textarea>
                    <input type="hidden" name="question_id" value="{{ quest.id }}">
                </div>
                <button type="submit" class="btn btn-default">Submit</button>
            </form>
    1. 显示评论次数
<h4>评论:({{ quest.comments|length }})</h4>

    1. 要求评论前登录
# 装饰器
def loginFrist(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if session.get('user'):
            return func(*args, **kwargs)
        else:
            return redirect(url_for('login'))
    return wrapper
    1. 尝试实现详情页面下的评论列表显示
原文地址:https://www.cnblogs.com/888abc/p/8004007.html