1.3新闻作者关注

做关注功能实现前我们得先修改新闻详情页得展示

1、前端代码(新闻作者信息

 1 {% if context.news.author %}
 2                 <div class="author_card">
 3                     <a href="#" class="author_pic"><img src="{% if context.news.author.avatar_url %}
 4                     {{ context.news.author.avatar_url }}
 5                     {% else %}
 6                     ../../static/news/images/user_pic.png
 7                     {% endif %}" alt="author_pic"></a>
 8                     <a href="#" class="author_name">{{ context.news.author.nick_name }}</a>
 9                     <div class="author_resume">签名:{{ context.news.author.signature }}</div>
10                     <div class="writings"><span>总篇数</span><b>{{ context.news.author.news_count }}</b></div>
11                     <div class="follows"><span>粉丝</span><b>{{ context.news.author.followers_count }}</b></div>
12 
13 
14                     <a href="javascript:;" class="focus fr" data-userid="{{ context.news.author.id }}" style="display: {% if context.is_followed %}none{% else %}block{% endif %}">关注</a>
15                     <a href="javascript:;" class="focused fr" data-userid="{{ context.news.author.id }}" style="display: {% if context.is_followed %}block{% else %}none{% endif %}"><span class="out">已关注</span><span class="over">取消关注</span></a>
16                 </div>
17             {% endif %}

  前端代码改完后我们还需要再详情页得视图函数中添加is_followed这个函数,用于判断是否关注新闻作者

  注:这里得判断我们用的反向查询,通过新闻找作者,可以在模型类中找到

   完成后得效果如下,关注按键没有效果,所以我们接着实现关注功能得实现

2、关注功能实现

 1 @news_index.route("/followed_user",methods=['POST'])
 2 @user_login_data
 3 def  followed_user():
 4     #获取用户信息
 5     user = g.user
 6     if not user:
 7         return jsonify(errno=RET.SERVERERR, errmsg="用户未登录")
 8     # 接收参数
 9     user_id = request.json.get("user_id", None)
10     action = request.json.get("action", None)
11     #校验参数是否为空
12     if not all([user_id, action]):
13         return jsonify(errno=RET.PARAMERR, errmsg="缺少参数")
14     #校验action中的参数是否为合法前端参数
15     if not action in ["follow", "unfollow"]:
16         return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
17     # 获取当前新闻的作者信息
18     try:
19         user_releaser = User.query.get(user_id)
20     except Exception as e:
21         current_app.logger.error(e)
22         return jsonify(errno=RET.NODATA, errmsg="未找到该用户")
23     #双分支处理action中的值
24     if action == "follow":
25         #判断作者的粉丝列表里是否有当前登录的用户
26         #写法二用户的关注列表里是否有新闻作者
27         #if not user_releaser in user.followed
28         #else中两种写法都可以
29         if user_releaser.followers.filter(User.id == g.user.id).count() > 0:
30             return jsonify(errno=RET.PARAMERR, errmsg="已经关注该用户")
31         else:
32             #添加到数据库
33             user_releaser.followers.append(user)
34 
35     else:
36         if user_releaser.followers.filter(User.id == g.user.id).count() > 0:
37             #删除数据库中的信息
38             user_releaser.followers.remove(g.user)
39         else:
40             return jsonify(errno=RET.PARAMERR, errmsg="未关注此用户")
41     try:
42         #数据提交
43         db.session.commit()
44     except Exception as e:
45         current_app.logger.error(e)
46         db.session.rollback()
47         return jsonify(errno=RET.DATAERR, errmsg="数据库存储失败")
48     #返回结果
49     return jsonify(errno=RET.OK, errmsg="成功")

  

  2.1js代码

 1      // 关注当前新闻作者
 2    $(".focus").click(function () {
 3     var user_id = $(this).attr('data-userid')
 4     var params = {
 5         "action": "follow",
 6         "user_id": user_id
 7     }
 8     $.ajax({
 9         url: "/news/followed_user",
10         type: "post",
11         contentType: "application/json",
12         headers: {
13             "X-CSRFToken": getCookie("csrf_token")
14         },
15         data: JSON.stringify(params),
16         success: function (resp) {
17             if (resp.errno == "0") {
18                 // 关注成功
19                 var count = parseInt($(".follows b").html());
20                 count++;
21                 $(".follows b").html(count + "")
22                 $(".focus").hide()
23                 $(".focused").show()
24             }else if (resp.errno == "4101"){
25                 // 未登录,弹出登录框
26                 $('.login_form_con').show();
27             }else {
28                 // 关注失败
29                 alert(resp.errmsg)
30             }
31         }
32     })
33 })
34 
35 // 取消关注当前新闻作者
36 $(".focused").click(function () {
37     var user_id = $(this).attr('data-userid')
38     var params = {
39         "action": "unfollow",
40         "user_id": user_id
41     }
42     $.ajax({
43         url: "/news/followed_user",
44         type: "post",
45         contentType: "application/json",
46         headers: {
47             "X-CSRFToken": getCookie("csrf_token")
48         },
49         data: JSON.stringify(params),
50         success: function (resp) {
51             if (resp.errno == "0") {
52                 // 取消关注成功
53                 var count = parseInt($(".follows b").html());
54                 count--;
55                 $(".follows b").html(count + "")
56                 $(".focus").show()
57                 $(".focused").hide()
58             }else if (resp.errno == "4101"){
59                 // 未登录,弹出登录框
60                 $('.login_form_con').show();
61             }else {
62                 // 取消关注失败
63                 alert(resp.errmsg)
64             }
65         }
66     })
67 })
68 })
原文地址:https://www.cnblogs.com/Hdwmsyqdm/p/14004154.html