41 - 个人博客项目-12-文章详情-点赞和评论

1. 编写点赞和评论函数 apps / article / views.py

# 点赞
@article_bp.route("/love")
def article_love():
    article_id = request.args.get('aid')
    tag = request.args.get('tag')
    article = Article.query.get(article_id)
    if tag == '1':
        article.love_num -= 1
    else:
        article.love_num += 1
    db.session.commit()
    return jsonify(num=article.love_num)
 
 
# 发表文章评论
@article_bp.route("/add_comment", methods=["GET", "POST"])
def article_comment():
    if request.method == "POST":
        comment_content = request.form.get('comment')
        user_id = g.user.id
        article_id = request.form.get('aid')
        # 评论模型
        comment = Comment()
        comment.comment = comment_content
        comment.user_id = user_id
        comment.article_id = article_id
        db.session.add(comment)
        db.session.commit()
        return redirect(url_for("article.article_detail") + "?aid=" + article_id)
    return redirect(url_for('user.index'))

2. templates / article / detail.html  编辑文章详情html;

        (1). 配置评论提交的路径
<form action="{{ url_for('article.article_comment') }}" method="post">
  .....
<form>
        (2). ajax实现点赞功能
{% block scripts %}
    {{ super() }}
    <script>
        $(function () {
            //收藏
            $(".glyphicon-heart").click(function () {

            });

            //点赞
            $(".glyphicon-thumbs-up").click(function () {
                let $this = $(this);
                let tag = $this.next("span").attr("tag");
                $.get('{{ url_for("article.article_love") }}', {aid:{{ article.id }}, tag: tag}, function (data) {
                    $this.next('span').text(data.num);
                });
                if (tag == 1) {
                    // 第二次点击(取消赞),tag=1,点击后执行一下代码,tag=0
                    $this.css({"color": "black"});
                    $this.next('span').attr('tag', "0");
                } else {
                    // 第一次点击(点赞),tag=0,点击后执行以下代码,tag=1
                    $this.css({"color": "red"});
                    $this.next('span').attr('tag', "1");

                }


            });


            //文本域
            $('textarea[name="comment"]').focus(function () {
                $(this).val("")
            })

        })
    </script>
{% endblock %}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值