完成评论功能
- 定义评论的视图函数
@app.route('/comment/',methods=['POST'])
def comment():
读取前端页面数据,保存到数据库中 - 用<input type="hidden" 方法获取前端的"question_id"
- 显示评论次数
- 要求评论前登录
- 尝试实现详情页面下的评论列表显示
def loginFirst(func): @wraps(func) def wrapper(*args, **kwargs): if session.get('user'): return func(*args, **kwargs) else: return redirect(url_for('sign_up')) return wrapper @app.route('/comment/', methods=['POST']) @loginFirst def comment(): comment = request.form.get("new_comment") question_id = request.form.get("question_id") author_id = User.query.filter(User.username == session.get('user')).first().id comm = Comment(author_id=author_id,question_id=question_id,detail=comment) db.session.add(comm) db.session.commit() context = { 'comments': Comment.query.order_by('creat_time').all() } question = Question.query.filter(Question.id == question_id).first() return render_template('question_detail.html', ques=question, **context)
{% extends'base.html' %} {% block title %} 详情* {% endblock %} {% block head %} <link rel="stylesheet" href="{{ url_for('static',filename='css/question_detail.css')}}" type="text/css"> {% endblock %} {% block main %} <body> <div class="detail"> <div class="detail_left"> <h3>{{ ques.question }}</h3> <a style="font-size: 18px">{{ ques.author.username }} <span class="badge">{{ ques.creat_time }}</span></a> <hr> <a>{{ ques.questionDetail }}</a> <hr> <form action="{{ url_for('comment') }}" method="post"> <textarea name="new_comment" class="form-control" rows="3" id="new_comment" placeholder="请写下你的评论..."></textarea> <input name="question_id" type="hidden" value="{{ ques.id }}"/> <br><button type="submit" class="btn-default">发布</button> </form> <h4>评论:({{ ques.comments|length }})</h4> <ul class="list-group"> {% for foo in ques.comments %} <li class="list-group-item"> <span class="glyphion-heart-empty" aria-hidden="true"></span> <a href="#">❤{{ foo.author.username }}</a> <span class="badge">{{ foo.creat_time }}</span> <p class="comdetail">{{ foo.detail }}</p> </li> {% endfor %} </ul> </div> </div> </body> {% endblock %}