Django实现翻页的示例代码


Posted in Python onMay 24, 2021

Django提供了翻页器。用Django的Paginator类实现

一、views模块导入Paginator类实现数据分页

ApiTest/apiviews.py

每行都加了注释,希望有助于理解。

from django.shortcuts import render
from ApiTest.models import ApiTest
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger, InvalidPage


@login_required
def api_test_manage(request):
    username = request.session.get('user', '')
    # 获取所有接口测试数据
    apitest_list = ApiTest.objects.all().order_by('id')
    # 生成Paginator对象对数据分页,每页显示10条数据
    paginator = Paginator(apitest_list,10)
    # 使用request.GET.get()函数获取url中的page参数的数值。默认第1页
    page = request.GET.get('page', 1)
    # 把获取的当前页码数转换成整数类型
    current_page = int(page)
    try:
     # 获取查询页数的接口数据列表,page()函数会判断page实参是否是有效数字。page()函数源码附在文章的最后
        apitest_list = paginator.page(page)
    except PageNotAnInteger:
        apitest_list = paginator.page(1)
    except (EmptyPage, InvalidPage):
     # paginator.num_pages
        apitest_list = paginator.page(paginator.num_pages)
    return render(request, "apitest_manage.html", {'user': username, 'apitests': apitest_list})

二、将views的数据渲染到前端模板上

在对应的html文件中加入此段代码即可。

<div class="container">
    <ul class="pagination" id="pager">
        {# 上一页链接 #}
        {% if apitests.has_previous %}
        <li class="previous"><a href="/apitest_manage/?page={{ apitests.previous_page_number }}" rel="external nofollow" >上一页</a></li>
        {% else %}
        <li class="previous disabled"><a href="#" rel="external nofollow"  rel="external nofollow" >上一页</a></li>
        {% endif %}

        {# 中间数字显示 #}
        {%  for num in apitests.paginator.page_range %}
            {%  if num == currentPage %}
                <li class="item active"><a href="/apitest_manage/?page={{ num }}" rel="external nofollow"  rel="external nofollow" >{{ num }}</a></li>
            {% else %}
                <li class="item"><a href="/apitest_manage/?page={{ num }}" rel="external nofollow"  rel="external nofollow" >{{ num }}</a></li>
            {% endif %}
        {% endfor %}

        {# 下一页链接 #}
        {% if apitests.has_next %}   {# 如果有下一页,则正常显示下一页链接 #}
            <li class="next"><a href="/apitest_manage/?page={{ apitests.next_page_number }}" rel="external nofollow" >下一页</a></li>
        {% else %}
            <li class="next disabled"><a href="#" rel="external nofollow"  rel="external nofollow" >下一页</a></li>
        {% endif %}

    </ul>
</div>

三、效果展示

Django实现翻页的示例代码

四、Paginator类源码

此类主要用在views文件

class Paginator:
    def __init__(self, object_list, per_page, orphans=0,
                 allow_empty_first_page=True):
        self.object_list = object_list
        self._check_object_list_is_ordered()
        self.per_page = int(per_page)
        self.orphans = int(orphans)
        self.allow_empty_first_page = allow_empty_first_page

    def validate_number(self, number):
        """Validate the given 1-based page number."""
        try:
            if isinstance(number, float) and not number.is_integer():
                raise ValueError
            number = int(number)
        except (TypeError, ValueError):
            raise PageNotAnInteger(_('That page number is not an integer'))
        if number < 1:
            raise EmptyPage(_('That page number is less than 1'))
        if number > self.num_pages:
            if number == 1 and self.allow_empty_first_page:
                pass
            else:
                raise EmptyPage(_('That page contains no results'))
        return number

    def get_page(self, number):
        """
        Return a valid page, even if the page argument isn't a number or isn't
        in range.
        """
        try:
            number = self.validate_number(number)
        except PageNotAnInteger:
            number = 1
        except EmptyPage:
            number = self.num_pages
        return self.page(number)

    def page(self, number):
        """Return a Page object for the given 1-based page number."""
        number = self.validate_number(number)
        bottom = (number - 1) * self.per_page
        top = bottom + self.per_page
        if top + self.orphans >= self.count:
            top = self.count
        return self._get_page(self.object_list[bottom:top], number, self)

    def _get_page(self, *args, **kwargs):
        """
        Return an instance of a single page.

        This hook can be used by subclasses to use an alternative to the
        standard :cls:`Page` object.
        """
        return Page(*args, **kwargs)

    @cached_property
    def count(self):
        """Return the total number of objects, across all pages."""
        c = getattr(self.object_list, 'count', None)
        if callable(c) and not inspect.isbuiltin(c) and method_has_no_args(c):
            return c()
        return len(self.object_list)

    @cached_property
    def num_pages(self):
        """Return the total number of pages."""
        if self.count == 0 and not self.allow_empty_first_page:
            return 0
        hits = max(1, self.count - self.orphans)
        return ceil(hits / self.per_page)

    @property
    def page_range(self):
        """
        Return a 1-based range of pages for iterating through within
        a template for loop.
        """
        return range(1, self.num_pages + 1)

    def _check_object_list_is_ordered(self):
        """
        Warn if self.object_list is unordered (typically a QuerySet).
        """
        ordered = getattr(self.object_list, 'ordered', None)
        if ordered is not None and not ordered:
            obj_list_repr = (
                '{} {}'.format(self.object_list.model, self.object_list.__class__.__name__)
                if hasattr(self.object_list, 'model')
                else '{!r}'.format(self.object_list)
            )
            warnings.warn(
                'Pagination may yield inconsistent results with an unordered '
                'object_list: {}.'.format(obj_list_repr),
                UnorderedObjectListWarning,
                stacklevel=3
            )

五、Page类源码

此类主要用在html文件

class Page(collections.abc.Sequence):

    def __init__(self, object_list, number, paginator):
        self.object_list = object_list
        self.number = number
        self.paginator = paginator

    def __repr__(self):
        return '<Page %s of %s>' % (self.number, self.paginator.num_pages)

    def __len__(self):
        return len(self.object_list)

    def __getitem__(self, index):
        if not isinstance(index, (int, slice)):
            raise TypeError(
                'Page indices must be integers or slices, not %s.'
                % type(index).__name__
            )
        # The object_list is converted to a list so that if it was a QuerySet
        # it won't be a database hit per __getitem__.
        if not isinstance(self.object_list, list):
            self.object_list = list(self.object_list)
        return self.object_list[index]

    def has_next(self):
        return self.number < self.paginator.num_pages

    def has_previous(self):
        return self.number > 1

    def has_other_pages(self):
        return self.has_previous() or self.has_next()

    def next_page_number(self):
        return self.paginator.validate_number(self.number + 1)

    def previous_page_number(self):
        return self.paginator.validate_number(self.number - 1)

    def start_index(self):
        """
        Return the 1-based index of the first object on this page,
        relative to total objects in the paginator.
        """
        # Special case, return zero if no items.
        if self.paginator.count == 0:
            return 0
        return (self.paginator.per_page * (self.number - 1)) + 1

    def end_index(self):
        """
        Return the 1-based index of the last object on this page,
        relative to total objects found (hits).
        """
        # Special case for the last page because there can be orphans.
        if self.number == self.paginator.num_pages:
            return self.paginator.count
        return self.number * self.paginator.per_page

到此这篇关于Django实现翻页的示例代码的文章就介绍到这了,更多相关Django 翻页内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python正则表达式修复网站文章字体不统一的解决方法
Feb 21 Python
Python实现从脚本里运行scrapy的方法
Apr 07 Python
python如何实现远程控制电脑(结合微信)
Dec 21 Python
浅谈Python中的可变对象和不可变对象
Jul 07 Python
import的本质解析
Oct 30 Python
Pycharm远程调试openstack的方法
Nov 21 Python
详解Python 多线程 Timer定时器/延迟执行、Event事件
Jun 27 Python
django 实现将本地图片存入数据库,并能显示在web上的示例
Aug 07 Python
pandas read_excel()和to_excel()函数解析
Sep 19 Python
Python浮点数四舍五入问题的分析与解决方法
Nov 19 Python
python自动脚本的pyautogui入门学习
Apr 01 Python
解决Python 函数声明先后顺序出现的问题
Sep 02 Python
pytorch--之halfTensor的使用详解
pandas DataFrame.shift()函数的具体使用
May 24 #Python
教你怎么用python实现字符串转日期
May 24 #Python
pandas中DataFrame重置索引的几种方法
May 24 #Python
pandas取dataframe特定行列的实现方法
pytorch 如何使用amp进行混合精度训练
只需要这一行代码就能让python计算速度提高十倍
You might like
通过html表格发电子邮件
2006/10/09 PHP
PHP中使用file_get_contents抓取网页中文乱码问题解决方法
2014/12/17 PHP
PHP+iframe模拟Ajax上传文件功能示例
2019/07/02 PHP
在修改准备发的批量美化select+可修改select时,在非IE下发现了几个问题
2007/01/09 Javascript
javascript 有趣而诡异的数组
2009/04/06 Javascript
IE8下关于querySelectorAll()的问题
2010/05/13 Javascript
js和jquery批量绑定事件传参数一(新猪猪原创)
2010/06/23 Javascript
JQuery 1.3.2以上版本中出现pareseerror错误的解决方法
2011/01/11 Javascript
JavaScript(js)设置默认输入焦点(focus)
2012/12/28 Javascript
JS日期和时间选择控件升级版(自写)
2013/08/02 Javascript
JS实现局部选择打印和局部不选择打印
2014/04/03 Javascript
JS实现先显示大图后自动收起显示小图的广告代码
2015/09/04 Javascript
微信公众号菜单配置微信小程序实例详解
2017/03/31 Javascript
使用vue框架 Ajax获取数据列表并用BootStrap显示出来
2017/04/24 Javascript
xmlplus组件设计系列之图标(ICON)(1)
2017/05/05 Javascript
JavaScript事件发布/订阅模式原理与用法分析
2018/08/21 Javascript
JS实现的小火箭发射动画效果示例
2018/12/08 Javascript
基于vue实现滚动条滚动到指定位置对应位置数字进行tween特效
2019/04/18 Javascript
Vue使用zTree插件封装树组件操作示例
2019/04/25 Javascript
layui实现左侧菜单点击右侧内容区显示
2019/07/26 Javascript
一个小示例告诉你Python语言的优雅之处
2014/07/04 Python
Python基于QRCode实现生成二维码的方法【下载,安装,调用等】
2017/07/11 Python
python基础_文件操作实现全文或单行替换的方法
2017/09/04 Python
django做form表单的数据验证过程详解
2019/07/26 Python
python自定义时钟类、定时任务类
2021/02/22 Python
CSS3教程(1):什么是CSS3
2009/04/02 HTML / CSS
如何用JQuery进行表单验证
2013/05/29 面试题
MYSQL基础面试题
2012/05/13 面试题
大学毕业感言一句话
2014/02/06 职场文书
网络书店创业计划书
2014/02/07 职场文书
网站美工岗位职责
2014/04/02 职场文书
开展党的群众路线教育实践活动领导班子对照检查材料
2014/09/25 职场文书
网络营销计划
2015/01/17 职场文书
建国70周年的心得体会(2篇)
2019/09/20 职场文书
《文化苦旅》读后感:阅读,让人诗意地栖居在大地上
2019/12/24 职场文书
我的收音机情缘
2022/04/05 无线电