Django 自定义分页器的实现代码


Posted in Python onNovember 24, 2019

为什么要实现分页?

在大部分网站中分页的功能都是必要的,尤其是在后台管理中分页更是不可或缺

分页能带给用户更好的体验,也能减轻服务器的压力

对于分页来说,有许多方法都可以实现

例如把数据全部读取出来在前端用javascript实现,但这样一次请求全部数据服务器压力很大,

还有就是在后端实现,每一次请求部分数据显示

分页需求:

1. 每页显示的多少条数据

2. 页面显示多少个页码

3. 上一页和下一页

4. 首页和尾页

效果演示:

Django 自定义分页器的实现代码

代码实现:

分页类封装:

在我的app下创建一个page.py文件,进行封装,我是先在我的app下创建了一个utils文件再创建page.py

Django 自定义分页器的实现代码

class Pagination(object):

  def __init__(self, current_page_num, all_count, request, per_page_num=10, pager_count=11):
    """
    封装分页相关数据
    :param current_page_num: 当前访问页的数字
    :param all_count:  分页数据中的数据总条数
    :param per_page_num: 每页显示的数据条数
    :param pager_count: 最多显示的页码个数
    """
    try:
      current_page_num = int(current_page_num)
    except Exception as e:
      current_page_num = 1

    if current_page_num < 1:
      current_page_num = 1

    self.current_page_num = current_page_num

    self.all_count = all_count
    self.per_page_num = per_page_num

    # 实际总页码
    all_pager, tmp = divmod(all_count, per_page_num)
    if tmp:
      all_pager += 1
    self.all_pager = all_pager

    self.pager_count = pager_count
    self.pager_count_half = int((pager_count - 1) / 2) # 5

    # 保存搜索条件
    import copy
    self.params = copy.deepcopy(request.GET) # {"a":"1","b":"2"}

  # 开始
  @property
  def start(self):
    return (self.current_page_num - 1) * self.per_page_num

  # 结束
  @property
  def end(self):
    return self.current_page_num * self.per_page_num

  # 实现
  def page_html(self):
    # 如果总页码 < 11个:
    if self.all_pager <= self.pager_count:
      pager_start = 1
      pager_end = self.all_pager + 1
    # 总页码 > 11
    else:
      # 当前页如果<=页面上最多显示11/2个页码
      if self.current_page_num <= self.pager_count_half:
        pager_start = 1
        pager_end = self.pager_count + 1
      # 当前页大于5
      else:
        # 页码翻到最后
        if (self.current_page_num + self.pager_count_half) > self.all_pager:

          pager_start = self.all_pager - self.pager_count + 1
          pager_end = self.all_pager + 1

        else:
          pager_start = self.current_page_num - self.pager_count_half
          pager_end = self.current_page_num + self.pager_count_half + 1

    page_html_list = []

    first_page = '<li><a href="?page=%s" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首页</a></li>' % (1,)
    page_html_list.append(first_page)

    if self.current_page_num <= 1:
      prev_page = '<li class="disabled"><a href="#" rel="external nofollow" rel="external nofollow" >上一页</a></li>'
    else:
      prev_page = '<li><a href="?page=%s" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >上一页</a></li>' % (self.current_page_num - 1,)

    page_html_list.append(prev_page)

    # self.params=copy.deepcopy(request.GET) # {"a":"1","b":"2"}

    for i in range(pager_start, pager_end):

      self.params["page"] = i

      if i == self.current_page_num:
        temp = '<li class="active"><a href="?%s" rel="external nofollow" rel="external nofollow" >%s</a></li>' % (self.params.urlencode(), i)
      else:
        temp = '<li><a href="?%s" rel="external nofollow" rel="external nofollow" >%s</a></li>' % (self.params.urlencode(), i,)
      page_html_list.append(temp)

    if self.current_page_num >= self.all_pager:
      next_page = '<li class="disabled"><a href="#" rel="external nofollow" rel="external nofollow" >下一页</a></li>'
    else:
      next_page = '<li><a href="?page=%s" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >下一页</a></li>' % (self.current_page_num + 1,)
    page_html_list.append(next_page)
    last_page = '<li><a href="?page=%s" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >尾页</a></li>' % (self.all_pager,)
    page_html_list.append(last_page)

    return ''.join(page_html_list)

在视图中使用

views.py

# 首先导入包
from myapp.utils.page import Pagination
from myapp.models import User


def index(request):
  # queryset
  user_list = User.objects.all()
  # 总页数
  page_count = user_list.count()
  # 当前页
  current_page_num = request.GET.get("page")
  pagination = Pagination(current_page_num, page_count, request, per_page_num=1)
  # 处理之后的数据
  user_list = user_list[pagination.start:pagination.end]

  content = {
    "user_list": user_list,
    "pagination": pagination,
  }
  return render(request, "user_list.html", content)

页面显示

user_list.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>index</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="external nofollow" >
</head>
<body>
<div class="container">
  <table class="table table-striped">
    <thead>
    <tr>
      <th>name</th>
    </tr>
    </thead>
    <tbody>
    {% for user in user_list %}
      <tr>
        <td>{{ user.name }}</td>
      </tr>
    {% endfor %}
    </tbody>
  </table>
  <!-- bootstrap 样式 -->
  <div class="dataTables_paginate paging_simple_numbers pull-right">
    <ul class="pagination">
      {{ pagination.page_html|safe }}
    </ul>
  </div>
</div>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
布同自制Python函数帮助查询小工具
Mar 13 Python
Python的gevent框架的入门教程
Apr 29 Python
Python调用SQLPlus来操作和解析Oracle数据库的方法
Apr 09 Python
python Pygame的具体使用讲解
Nov 03 Python
Python实现比较扑克牌大小程序代码示例
Dec 06 Python
浅谈Python实现Apriori算法介绍
Dec 20 Python
在python中利用numpy求解多项式以及多项式拟合的方法
Jul 03 Python
Python 实用技巧之利用Shell通配符做字符串匹配
Aug 23 Python
python使用gdal对shp读取,新建和更新的实例
Mar 10 Python
Python通过类的组合模拟街道红绿灯
Sep 16 Python
Python中with上下文管理协议的作用及用法
Mar 18 Python
python DataFrame中stack()方法、unstack()方法和pivot()方法浅析
Apr 06 Python
基于python的列表list和集合set操作
Nov 24 #Python
使用Pyhton集合set()实现成果查漏的例子
Nov 24 #Python
Python完全识别验证码自动登录实例详解
Nov 24 #Python
关于Python 常用获取元素 Driver 总结
Nov 24 #Python
pyhton中__pycache__文件夹的产生与作用详解
Nov 24 #Python
使用Python实现画一个中国地图
Nov 23 #Python
用Python画小女孩放风筝的示例
Nov 23 #Python
You might like
帅气的琦玉老师
2020/03/02 日漫
如何使用FireFox插件FirePHP调试PHP
2013/07/23 PHP
Zend Framework开发入门经典教程
2016/03/23 PHP
利用PHP如何写APP接口详解
2016/08/23 PHP
关于实现代码语法标亮 dp.SyntaxHighlighter
2007/02/02 Javascript
基于jQuery中对数组进行操作的方法
2013/04/16 Javascript
jquery如何实现锚点链接之间的平滑滚动
2013/12/02 Javascript
JavaScript实现twitter puddles算法实例
2014/12/06 Javascript
浅谈javascript 函数属性和方法
2015/01/21 Javascript
使用Javascript实现选择下拉菜单互移并排序
2016/02/23 Javascript
JS正则表达式完美实现身份证校验功能
2017/10/18 Javascript
nodejs实现一个word文档解析器思路详解
2018/08/14 NodeJs
js实现数字从零慢慢增加到指定数字示例
2019/11/07 Javascript
在vue-cli3中使用axios获取本地json操作
2020/07/30 Javascript
浅谈python中的实例方法、类方法和静态方法
2017/02/17 Python
python利用paramiko连接远程服务器执行命令的方法
2017/10/16 Python
Python中多个数组行合并及列合并的方法总结
2018/04/12 Python
Python实现带参数的用户验证功能装饰器示例
2018/12/14 Python
python调用matlab的m自定义函数方法
2019/02/18 Python
关于Python 的简单栅格图像边界提取方法
2019/07/05 Python
pycharm下pyqt4安装及环境配置的教程
2020/04/24 Python
python 代码实现k-means聚类分析的思路(不使用现成聚类库)
2020/06/01 Python
利用CSS3伪元素实现逐渐发光的方格边框
2017/05/07 HTML / CSS
同学聚会主持词
2014/03/18 职场文书
《画风》教学反思
2014/04/16 职场文书
信用社主任竞聘演讲稿
2014/05/23 职场文书
11.9消防日宣传标语
2014/10/08 职场文书
学校勤俭节约倡议书
2015/04/29 职场文书
入党积极分子培养联系人意见
2015/08/12 职场文书
2016年党支部公开承诺书
2016/03/25 职场文书
导游词之天津盘山
2019/11/01 职场文书
MySQL注入基础练习
2021/05/30 MySQL
使用Nginx搭载rtmp直播服务器的方法
2021/10/16 Servers
Java中API的使用方法详情
2022/04/06 Java/Android
Python编写冷笑话生成器
2022/04/20 Python
教你使用Ubuntu搭建DNS服务器
2022/09/23 Servers