Django框架 Pagination分页实现代码实例


Posted in Python onSeptember 04, 2019

一、自定义分页

1、基础版自定义分页

data = []
 
for i in range(1, 302):
  tmp = {"id": i, "name": "alex-{}".format(i)}
  data.append(tmp)
 
print(data)
def user_list(request):
 
  # user_list = data[0:10]
  # user_list = data[10:20]
  try:
    current_page = int(request.GET.get("page"))
  except Exception as e:
    current_page = 1
 
  per_page = 10
 
  # 数据总条数
  total_count = len(data)
  # 总页码
  total_page, more = divmod(total_count, per_page)
  if more:
    total_page += 1
 
  # 页面最多显示多少个页码
  max_show = 11
  half_show = int((max_show-1)/2)
 
  if current_page <= half_show:
    show_start = 1
    show_end = max_show
  else:
    if current_page + half_show >= total_page:
      show_start = total_page - max_show
      show_end = total_page
    else:
      show_start = current_page - half_show
      show_end = current_page + half_show
 
  # 数据库中获取数据
  data_start = (current_page - 1) * per_page
  data_end = current_page * per_page
 
  user_list = data[data_start:data_end]
 
  # 生成页面上显示的页码
  page_html_list = []
  # 加首页
  first_li = '<li><a href="/user_list/?page=1" rel="external nofollow" >首页</a></li>'
  page_html_list.append(first_li)
  # 加上一页
  if current_page == 1:
    prev_li = '<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >上一页</a></li>'
  else:
    prev_li = '<li><a href="/user_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >上一页</a></li>'.format(current_page - 1)
  page_html_list.append(prev_li)
  for i in range(show_start, show_end+1):
    if i == current_page:
      li_tag = '<li class="active"><a href="/user_list/?page={0}" rel="external nofollow" rel="external nofollow" >{0}</a></li>'.format(i)
    else:
      li_tag = '<li><a href="/user_list/?page={0}" rel="external nofollow" rel="external nofollow" >{0}</a></li>'.format(i)
    page_html_list.append(li_tag)
 
  # 加下一页
  if current_page == total_page:
    next_li = '<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >下一页</a></li>'
  else:
    next_li = '<li><a href="/user_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >下一页</a></li>'.format(current_page+1)
  page_html_list.append(next_li)
 
  # 加尾页
  page_end_li = '<li><a href="/user_list/?page={}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >尾页</a></li>'.format(total_page)
  page_html_list.append(page_end_li)
 
  page_html = "".join(page_html_list)
 
  return render(request, "user_list.html", {"user_list": user_list, "page_html": page_html})

2、封装保存版

class Pagination(object):
  def __init__(self, current_page, total_count, base_url, per_page=10, max_show=11):
    """
    :param current_page: 当前页
    :param total_count: 数据库中数据总数
    :param per_page: 每页显示多少条数据
    :param max_show: 最多显示多少页
    """
    try:
      current_page = int(current_page)
    except Exception as e:
      current_page = 1
 
    self.current_page = current_page
    self.total_count = total_count
    self.base_url = base_url
    self.per_page = per_page
    self.max_show = max_show
 
    # 总页码
    total_page, more = divmod(total_count, per_page)
    if more:
      total_page += 1
     
    half_show = int((max_show - 1) / 2)
    self.half_show = half_show
    self.total_page = total_page
 
  @property
  def start(self):
    return (self.current_page - 1) * self.per_page
 
  @property
  def end(self):
    return self.current_page * self.per_page
 
  def page_html(self):
 
    if self.current_page <= self.half_show:
      show_start = 1
      show_end = self.max_show
    else:
      if self.current_page + self.half_show >= self.total_page:
        show_start = self.total_page - self.max_show
        show_end = self.total_page
      else:
        show_start = self.current_page - self.half_show
        show_end = self.current_page + self.half_show
 
        # 生成页面上显示的页码
    page_html_list = []
    # 加首页
    first_li = '<li><a href="{}?page=1" rel="external nofollow" >首页</a></li>'.format(self.base_url)
    page_html_list.append(first_li)
    # 加上一页
    if self.current_page == 1:
      prev_li = '<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >上一页</a></li>'
    else:
      prev_li = '<li><a href="{0}?page={1}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >上一页</a></li>'.format(self.base_url, self.current_page - 1)
    page_html_list.append(prev_li)
    for i in range(show_start, show_end + 1):
      if i == self.current_page:
        li_tag = '<li class="active"><a href="{0}?page={1}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{1}</a></li>'.format(self.base_url, i)
      else:
        li_tag = '<li><a href="{0}?page={1}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{1}</a></li>'.format(self.base_url, i)
      page_html_list.append(li_tag)
     # 加下一页
    if self.current_page == self.total_page:
      next_li = '<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >下一页</a></li>'
    else:
      next_li = '<li><a href="{0}?page={1}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >下一页</a></li>'.format(self.base_url, self.current_page + 1)
    page_html_list.append(next_li)
 
    # 加尾页
    page_end_li = '<li><a href="{0}?page={1}" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >尾页</a></li>'.format(self.base_url, self.total_page)
    page_html_list.append(page_end_li)
     return "".join(page_html_list)

3、封装保存版使用指南

def user_list(request):
  pager = Pagination(request.GET.get("page"), len(data), request.path_info)
  user_list = data[pager.start:pager.end]
  page_html = pager.page_html()
  return render(request, "user_list.html", {"user_list": user_list, "page_html": page_html})

二、Django内置分页

1、内置分页view部分

from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
L = []
for i in range(999):
  L.append(i)
def index(request):
  current_page = request.GET.get('p')
  paginator = Paginator(L, 10)
  # per_page: 每页显示条目数量
  # count:  数据总个数
  # num_pages:总页数
  # page_range:总页数的索引范围,如: (1,10),(1,200)
  # page:   page对象
  try:
    posts = paginator.page(current_page)
    # has_next       是否有下一页
    # next_page_number   下一页页码
    # has_previous     是否有上一页
    # previous_page_number 上一页页码
    # object_list      分页之后的数据列表
    # number        当前页
    # paginator       paginator对象
  except PageNotAnInteger:
    posts = paginator.page(1)
  except EmptyPage:
    posts = paginator.page(paginator.num_pages)
  return render(request, 'index.html', {'posts': posts}) 

2、内置分页HTML部分

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
<ul>
  {% for item in posts %}
    <li>{{ item }}</li>
  {% endfor %}
</ul>
 
<div class="pagination">
   <span class="step-links">
    {% if posts.has_previous %}
      <a href="?p={{ posts.previous_page_number }}" rel="external nofollow" >Previous</a>
    {% endif %}
     <span class="current">
      Page {{ posts.number }} of {{ posts.paginator.num_pages }}.
     </span>
     {% if posts.has_next %}
       <a href="?p={{ posts.next_page_number }}" rel="external nofollow" >Next</a>
     {% endif %}
   </span>
</div>
</body>
</html>

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

Python 相关文章推荐
Python实现求最大公约数及判断素数的方法
May 26 Python
Python语言描述随机梯度下降法
Jan 04 Python
对python GUI实现完美进度条的示例详解
Dec 13 Python
在python 中实现运行多条shell命令
Jan 07 Python
python调用并链接MATLAB脚本详解
Jul 05 Python
解决Django加载静态资源失败的问题
Jul 28 Python
如何完美的建立一个python项目
Oct 09 Python
Python创建文件夹与文件的快捷方法
Dec 08 Python
Python如何使用logging为Flask增加logid
Mar 30 Python
Python 处理表格进行成绩排序的操作代码
Jul 26 Python
python实现双链表
May 25 Python
如何利用python创作字符画
Jun 25 Python
python 动态迁移solr数据过程解析
Sep 04 #Python
Django框架 信号调度原理解析
Sep 04 #Python
Django Admin中增加导出Excel功能过程解析
Sep 04 #Python
Django Admin中增加导出CSV功能过程解析
Sep 04 #Python
Python 自动登录淘宝并保存登录信息的方法
Sep 04 #Python
通过Python编写一个简单登录功能过程解析
Sep 04 #Python
利用 Flask 动态展示 Pyecharts 图表数据方法小结
Sep 04 #Python
You might like
PHP 加密/解密函数 dencrypt(动态密文,带压缩功能,支持中文)
2009/01/30 PHP
PHP 一个比较完善的简单文件上传
2010/03/25 PHP
thinkPHP实现表单自动验证
2014/12/24 PHP
PHP实现百度人脸识别
2019/05/06 PHP
[原创]提供复制本站内容时出现,该文章转自脚本之家等字样的js代码
2007/03/27 Javascript
Javascript &amp; DHTML 实例编程(教程)DOM基础和基本API
2007/06/02 Javascript
Js点击弹出下拉菜单效果实例
2013/08/12 Javascript
div模拟选择框示例代码
2013/11/03 Javascript
jQuery与getJson结合的用法实例
2015/08/07 Javascript
JS实现黑客帝国文字下落效果
2015/09/01 Javascript
prototype.js常用函数详解
2016/06/18 Javascript
JS实现根据文件字节数返回文件大小的方法
2016/08/02 Javascript
微信小程序 wx.uploadFile在安卓手机上面the same task is working问题解决
2016/12/14 Javascript
vue 本地环境跨域请求proxyTable的方法
2018/09/19 Javascript
angular 未登录状态拦截路由跳转的方法
2018/10/09 Javascript
bootstrap-table后端分页功能完整实例
2020/06/01 Javascript
pyqt和pyside开发图形化界面
2014/01/22 Python
Python中List.index()方法的使用教程
2015/05/20 Python
分享Pycharm中一些不为人知的技巧
2018/04/03 Python
python 公共方法汇总解析
2019/09/16 Python
Python学习笔记之函数的参数和返回值的使用
2019/11/20 Python
Python面向对象封装操作案例详解 II
2020/01/02 Python
英国排名第一的最新设计师品牌手表独立零售商:TIC Watches
2016/09/24 全球购物
上海奥佳笔试题面试题
2016/11/16 面试题
大学生的自我鉴定范文
2014/01/21 职场文书
数控技术学生的自我评价
2014/02/15 职场文书
改作风抓落实促发展心得体会
2014/09/10 职场文书
党员四风自我剖析材料思想汇报
2014/09/13 职场文书
卫校毕业生自我鉴定
2014/09/28 职场文书
乡镇民主生活会发言材料
2014/10/20 职场文书
2014年管理工作总结
2014/11/22 职场文书
教导主任个人总结
2015/03/03 职场文书
安全责任协议书范本
2016/03/23 职场文书
springboot集成springCloud中gateway时启动报错的解决
2021/07/16 Java/Android
鲲鹏 CentOS 7 安装Python3.7
2022/05/11 Servers
HTML中link标签属性的具体用法
2023/05/07 HTML / CSS