完成评论功能

1.定义评论的视图函数
@app.route('/comment/',methods=['POST'])
def comment():
读取前端页面数据,保存到数据库中

@app.route('/comment/',methods=['POST'])
def comment():
    comment=request.form.get('new_comment')
    ques_id=request.form.get('question_id')
    auth_id=User.query.filter(User.username == session.get('user')).first().id
    comm =Comment(author_id=auth_id,question_id=ques_id,detail=comment)
    db.session.add(comm)
    db.session.commit()
    return redirect(url_for('detail'),question_id=ques_id)

2.用<input type="hidden" 方法获取前端的"question_id" 

<div class="page-header">
    <h3>{{ ques.title }}<br><br>
    <small>作者:{{ ques.author.username }}
    <span class="badge">{{ ques.creat_time }}</span>
        </small></h3>
</div>
            <p class="lead">{{ ques.detail }}</p>
            <hr>
            <form action="{{ url_for('comment') }}" method="post" style="margin:20px">
                <div class="form-group">
                    <input type="text" value="{{ ques.id }}" name="question_id" hidden>
                    <input type="text" value="{{ user.id }}" name="author_id" hidden>
                    <textarea name="new comment" class="form-control"  row="3" id="new-comment" placeholder="write your comment"></textarea>
                    <input type="hidden" name="question_id" value="{{ ques.id }}">
                </div>
                <button type="submit" class="btn btn-default">发送</button>
            </form>
        <hr>
            <h4>评论:({{  ques.comments|length}})</h4>

3.显示评论次数

<h4>评论:({{  ques.comments|length}})</h4>

4.要求评论前登录

def loginFirst(func):  
    @wraps(func)
    def wrapper(*args, **kwargs):  
        if session.get('user'):
            return func(*args, **kwargs)
        else:
            return redirect(url_for('login'))
    return wrapper  


@app.route('/comment/',methods=['POST'])
@loginFirst
def comment():
    if request.method == 'POST':
        comment= request.form.get('detail')
        question_id = request.form.get('question_id')
        # author_id = request.form.get('author_id')
        author_id=User.query.filter(User.username==session.get('user')).first().id
        detail = request.form.get('detail')
        com = Comment(question_id=question_id, author_id=author_id, detail=detail)
        db.session.add(com)
        db.session.commit()
        return redirect(url_for('detail',question_id=question_id))

5.尝试实现详情页面下的评论列表显示

 <ul class="list-unstyled">
                {% for foo in comments %}
                    <li class="list-group-item">
                        <a>{{ foo.author.username }}</a>
                        <span class="badge pull-right">{{ foo.creat_time }}</span>
                        <p>{{ foo.detail }}</p>
                        <br>
                    </li>
                {% endfor %}
            </ul>
posted @ 2017-12-08 18:29  047连薇娜  阅读(167)  评论(0编辑  收藏  举报