1.4用户收藏展示

首先用户收藏展示的效果如下

 1、我的首先将静态前端添加到templates模板中

(注:这里可以不用放进来的,因为收藏的页面并没有表单的提交,但是为了规范所以最好是放进来

2、下面是前端的代码(html和js写在一起的)

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>用户中心</title>
 6     <link rel="stylesheet" type="text/css" href="../../static/news/css/reset.css">
 7     <link rel="stylesheet" type="text/css" href="../../static/news/css/jquery.pagination.css">
 8     <link rel="stylesheet" type="text/css" href="../../static/news/css/main.css">
 9     <script type="text/javascript" src="../../static/news/js/jquery-1.12.4.min.js"></script>
10     <script type="text/javascript" src="../../static/news/js/jquery.pagination.min.js"></script>
11 </head>
12 <body class="inframe_body">
13     <div class="my_collect">
14         <h3>我的收藏</h3>
15         <ul class="article_list">
16             {% for news in context.news_list %}
17                 <li><a href="#">{{ news.title }}</a><span>{{ news.create_time }}</span></li>
18             {% endfor %}
19         </ul>
20 
21 
22 
23         <div id="pagination" class="page"></div>
24         <script>
25 {#            这是使用的是分页框架#}
26             $(function() {
27                 $("#pagination").pagination({
28                     currentPage: {{ context.current_page }},
29                     totalPage: {{ context.total_page }},
30 {#                    当用户的鼠标点击哪一页的时候自动执行下面的事件#}
31                     callback: function(current) {
32                         window.location.href = '/user/user_collection?p=' + current;
33                     }
34                 });
35             });
36         </script>
37 
38     </div>
39 </body>
40 </html>

3、以下为后台视图函数的代码

 1 @user_blue.route("/user_collection")
 2 @user_login_data
 3 def user_collection():
 4     user = g.user
 5     # 接收用户信息同时判断是否登录
 6     if not user:
 7         return redirect(url_for('index.index'))
 8     #接收前端通过get请求传来的p参数
 9     page = request.args.get("p")
10     try:
11         #将接收来的参数强转为int类型
12         page = int(page)
13     except Exception as e:
14         current_app.logger.error(e)
15         #二次保障设置默认值为1
16         page = 1
17     try:
18         #获取用户收藏的新闻列表并使用分页器接收
19         paginate = user.collection_news.paginate(page=page,per_page=constants.USER_FOLLOWED_MAX_COUNT)
20     except Exception as e:
21         current_app.logger.error(e)
22         return jsonify(errno=RET.DATAERR, errmsg="查询失败")
23     #获取所有的新闻数据
24     newsList = paginate.items
25     #新闻一页最多显示多少条数据
26     totalPage = paginate.pages
27     #新闻页数
28     currentPage = paginate.page
29     #返回上下文
30     context = {
31         "total_page":totalPage,
32         "news_list" :newsList,
33         "current_page":currentPage,
34     }
35     return render_template("news/user_collection.html",context=context)

(注:有一点需要注意我们在接收完前端传来的p的值后打断点会发现它的值为NoneType,为什么会出现这个结果呢?

  原因是你个人中心页中没有给他说明默认值,需要我们手动设置,最好把后台也设置以下,双重保障

 

 以上就是全部的代码编写了

原文地址:https://www.cnblogs.com/Hdwmsyqdm/p/13930528.html