分页器推导

"""
总数据100 每页展示10 需要10
总数据101 每页展示10 需要11
总数据99 每页展示10  需要10

如何通过代码动态的计算出到底需要多少页?

在制作页码个数的时候 一般情况下都是奇数个        符合对称美的标准
"""

初步推导:

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # 分页
    url(r'^ab_batch',views.ab_batch),
]

views.py

from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from app01 import models

def ab_batch(request):
    # 分页器推导
    book_list = models.Book.objects.all()
    # 想访问哪一页
    current_page = request.GET.get('page', 1)  # 如果获取不到当前页码 就展示第一页
    # 数据类型转换
    try:
        current_page = int(current_page)
    except Exception:
        current_page = 1

    # 每页展示多少条
    per_page_num = 10
    # 起始位置
    start_page = (current_page - 1) * per_page_num
    # 终止位置
    end_page = current_page * per_page_num

    # 计算出到底需要多少页
    all_count = book_list.count()

    page_count, more = divmod(all_count, per_page_num)
    if more:
        page_count += 1

    if current_page <= 1:
        prev_page = '<li class="disabled"><a href="#">上一页</a></li>'
    else:
        prev_page = '<li><a href="?page=%s">上一页</a></li>' % (current_page - 1,)
    page_html = ''
    current_page_new = current_page
    if current_page < 6:
        current_page = 6
    for i in range(current_page - 5, current_page + 6):
        if current_page_new == i:
            page_html += '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i)
        else:
            page_html += '<li><a href="?page=%s">%s</a></li>' % (i, i)

    if current_page >= page_count:
        next_page = '<li class="disabled"><a href="#">下一页</a></li>'
    else:
        next_page = '<li><a href="?page=%s">下一页</a></li>' % (current_page + 1,)


    book_queryset = book_list[start_page:end_page]

    return render(request,"ab_batch.html",locals())
'''
per_page_num = 10
current_page                start_page                  end_page
    1                           0                           10
    2                           10                          20
    3                           20                          30
    4                           30                          40

per_page_num = 5
current_page                start_page                  end_page
    1                           0                           5
    2                           5                           10
    3                           15                          20
    4                           25                          30

规律:
start_page = (current_page - 1) * per_page_num
end_page = current_page * per_page_num
'''

ab_batch.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- Bootstrap3 核心 CSS 文件 -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <!-- Bootstrap3 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!-- font-awesome.min.css图标库4.7版本 -->
    <link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body>
{% for book_obj in book_queryset %}
    <p>{{ book_obj.title }}</p>
{% endfor %}

<div class="text-center">
    <nav aria-label="Page navigation">
    <ul class="pagination ">
    <li><a href="?page=1">首页</a></li>
    {{ prev_page|safe }}
    {{ page_html|safe }}
    {{ next_page|safe }}
    <li><a href="?page={{ page_count }}">尾部</a></li>
    </ul>
    </nav>
</div>

</body>
</html>

推导过程

1.queryset对象是直接切片操作的
  2.用户到底要访问哪一页 如何确定?        url?page=1
      current_page = request.GET.get('page',1)
    # 获取到的数据都是字符串类型 你需要注意类型转换
  3.自己规定每页展示多少条数据
      per_page_num = 10
  4.切片的起始位置和终止位置
      start_page = (current_page - 1)* per_page_num
    end_page = current_page * per_page_num
    # 利用简单找规律 找出上述四个参数的规律
  5.当前数据的总条数
      book_queryset.count()
  6.如何确定总共需要多少页才能展示完所有的数据
      # 利用python内置函数divmod()
    page_count, more = divmod(all_count,per_page_num)
    if more:
      page_count += 1
  7.前端模版语法是没有range功能的
      # 前端代码不一定非要在前端书写 也可以在后端生成传递给页面
  8.针对需要展示的页码需要你自己规划好到底展示多少个页码
      # 一般情况下页码的个数设计都是奇数(符合审美标准)  11个页码
    当前页减5
    当前页加6
    你可以给标签价样式从而让选中的页码高亮显示
  9.针对页码小于6的情况 你需要做处理 不能再减

终极版分页器

初级版是自定义分页器开发流程的基本思路,我们不需要掌握代码的编写,只需要掌握基本用法即可

自定义分页器封装代码

注意:

自定义的分页器是基于bootstrap样式来的 所以需要提前导入bootstrap
bootstrap 版本 v3
jQuery 版本 v3

# 分页器
class Pagination(object):
    def __init__(self, current_page, all_count, per_page_num=2, pager_count=11):
        """
        封装分页相关数据
        :param current_page: 当前页
        :param all_count:    数据库中的数据总条数
        :param per_page_num: 每页显示的数据条数
        :param pager_count:  最多显示的页码个数
        """
        try:
            current_page = int(current_page)
        except Exception as e:
            current_page = 1

        if current_page < 1:
            current_page = 1

        self.current_page = current_page

        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)

    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_num

    @property
    def end(self):
        return self.current_page * 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 <= self.pager_count_half:
                pager_start = 1
                pager_end = self.pager_count + 1

            # 当前页大于5
            else:
                # 页码翻到最后
                if (self.current_page + self.pager_count_half) > self.all_pager:
                    pager_end = self.all_pager + 1
                    pager_start = self.all_pager - self.pager_count + 1
                else:
                    pager_start = self.current_page - self.pager_count_half
                    pager_end = self.current_page + self.pager_count_half + 1

        page_html_list = []
        # 添加前面的nav和ul标签
        page_html_list.append('''
                  <nav aria-label='Page navigation>'
                      <ul class='pagination'>
                            ''')
        first_page = '<li><a href="?page=%s">首页</a></li>' % (1)
        page_html_list.append(first_page)

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

        page_html_list.append(prev_page)

        for i in range(pager_start, pager_end):
            if i == self.current_page:
                temp = '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i,)
            else:
                temp = '<li><a href="?page=%s">%s</a></li>' % (i, i,)
            page_html_list.append(temp)

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

        last_page = '<li><a href="?page=%s">尾页</a></li>' % (self.all_pager,)
        page_html_list.append(last_page)
        # 尾部添加标签
        page_html_list.append('''
                      </ul>
                   </nav>
                ''')
        return ''.join(page_html_list)

自定义分页器拷贝及使用

"""
当我们需要使用到非django内置的第三方功能或者组件代码的时候
我们一般情况下会在项目根目录创建一个名为utils文件夹 在该文件夹内对模块进行功能性划分
    utils也可以可以在每个应用下创建 具体结合实际情况

我们到了后期封装代码的时候 不再局限于函数
还是尽量朝面向对象去封装

我们自定义的分页器是基于bootstrap样式来的 所以你需要提前导入bootstrap
    bootstrap 版本 v3
    jQuery        版本 v3
"""

1、在django项目根目录或app01应用目录新建一个utils文件夹用于存放第三方功能或模块

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # 分页
    url(r'^ab_batch',views.ab_batch),
]

mypage.py

# 分页器
class Pagination(object):
    def __init__(self, current_page, all_count, per_page_num=2, pager_count=11):
        """
        封装分页相关数据
        :param current_page: 当前页
        :param all_count:    数据库中的数据总条数
        :param per_page_num: 每页显示的数据条数
        :param pager_count:  最多显示的页码个数
        """
        try:
            current_page = int(current_page)
        except Exception as e:
            current_page = 1

        if current_page < 1:
            current_page = 1

        self.current_page = current_page

        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)

    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_num

    @property
    def end(self):
        return self.current_page * 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 <= self.pager_count_half:
                pager_start = 1
                pager_end = self.pager_count + 1

            # 当前页大于5
            else:
                # 页码翻到最后
                if (self.current_page + self.pager_count_half) > self.all_pager:
                    pager_end = self.all_pager + 1
                    pager_start = self.all_pager - self.pager_count + 1
                else:
                    pager_start = self.current_page - self.pager_count_half
                    pager_end = self.current_page + self.pager_count_half + 1

        page_html_list = []
        # 添加前面的nav和ul标签
        page_html_list.append('''
                  <nav aria-label='Page navigation>'
                      <ul class='pagination'>
                            ''')
        first_page = '<li><a href="?page=%s">首页</a></li>' % (1)
        page_html_list.append(first_page)

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

        page_html_list.append(prev_page)

        for i in range(pager_start, pager_end):
            if i == self.current_page:
                temp = '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i,)
            else:
                temp = '<li><a href="?page=%s">%s</a></li>' % (i, i,)
            page_html_list.append(temp)

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

        last_page = '<li><a href="?page=%s">尾页</a></li>' % (self.all_pager,)
        page_html_list.append(last_page)
        # 尾部添加标签
        page_html_list.append('''
                      </ul>
                   </nav>
                ''')
        return ''.join(page_html_list)

mypage.py

views.py后端使用

from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from app01 import models
from utils.mypage import Pagination    # 导入分页器,这里utils文件夹在根目录下,如果在app01应用目录下使用from app01.utils.mypage import Pagination

def ab_batch(request):
    # 分页器推导
    book_list = models.Book.objects.all()
    # 想访问哪一页
    current_page = request.GET.get('page', 1)  # 如果获取不到当前页码 就展示第一页

    # 计算出到底需要多少页
    all_count = book_list.count()

    page_obj = Pagination(current_page=current_page, all_count=all_count, per_page_num=10)
    page_queryset = book_list[page_obj.start:page_obj.end]
    return render(request, 'ab_batch.html', locals())

前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- Bootstrap3 核心 CSS 文件 -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <!-- Bootstrap3 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!-- font-awesome.min.css图标库4.7版本 -->
    <link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body>
{% for book_obj in book_queryset %}
    <p>{{ book_obj.title }}</p>
{% endfor %}

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            {% for book in page_queryset %}
            <p>{{ book.title }}</p>
            {% endfor %}            <div class="text-center">
                {{ page_obj.page_html|safe }}            </div>
        </div>
    </div>
</div>

</body>
</html>

Django自带的分页器(paginator)简介

在页面显示分页数据,需要用到Django分页器组件

from django.core.paginator import Paginator
Paginator对象:    paginator = Paginator(user_list, 10)
# per_page: 每页显示条目数量
# count:    数据总个数
# num_pages:总页数
# page_range:总页数的索引范围,如: (1,10),(1,200)
# page:     page对象    
page对象:page=paginator.page(1)
# has_next              是否有下一页
# next_page_number      下一页页码
# has_previous          是否有上一页
# previous_page_number  上一页页码
# object_list           分页之后的数据列表
# number                当前页
# paginator             paginator对象

应用view层

from django.shortcuts import render,HttpResponse

# Create your views here.
from app01.models import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def index(request):

    '''
    批量导入数据:

    Booklist=[]
    for i in range(100):
        Booklist.append(Book(title="book"+str(i),price=30+i*i))
    Book.objects.bulk_create(Booklist)
    '''

    '''
分页器的使用:

    book_list=Book.objects.all()

    paginator = Paginator(book_list, 10)

    print("count:",paginator.count)           #数据总数
    print("num_pages",paginator.num_pages)    #总页数
    print("page_range",paginator.page_range)  #页码的列表



    page1=paginator.page(1) #第1页的page对象
    for i in page1:         #遍历第1页的所有数据对象
        print(i)

    print(page1.object_list) #第1页的所有数据


    page2=paginator.page(2)

    print(page2.has_next())            #是否有下一页
    print(page2.next_page_number())    #下一页的页码
    print(page2.has_previous())        #是否有上一页
    print(page2.previous_page_number()) #上一页的页码



    # 抛错
    #page=paginator.page(12)   # error:EmptyPage

    #page=paginator.page("z")   # error:PageNotAnInteger

    '''


    book_list=Book.objects.all()

    paginator = Paginator(book_list, 10)
    page = request.GET.get('page',1)
    currentPage=int(page)


    try:
        print(page)
        book_list = paginator.page(page)
    except PageNotAnInteger:
        book_list = paginator.page(1)
    except EmptyPage:
        book_list = paginator.page(paginator.num_pages)


    return render(request,"index.html",{"book_list":book_list,"paginator":paginator,"currentPage":currentPage})

模板层

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" 
    integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>

<div class="container">

    <h4>分页器</h4>
    <ul>

        {% for book in book_list %}
             <li>{{ book.title }} -----{{ book.price }}</li>
        {% endfor %}

     </ul>


    <ul class="pagination" id="pager">

                 {% if book_list.has_previous %}
                    <li class="previous"><a href="/index/?page={{ book_list.previous_page_number }}">上一页</a></li>
                 {% else %}
                    <li class="previous disabled"><a href="#">上一页</a></li>
                 {% endif %}


                 {% for num in paginator.page_range %}

                     {% if num == currentPage %}
                       <li class="item active"><a href="/index/?page={{ num }}">{{ num }}</a></li>
                     {% else %}
                       <li class="item"><a href="/index/?page={{ num }}">{{ num }}</a></li>

                     {% endif %}
                 {% endfor %}



                 {% if book_list.has_next %}
                    <li class="next"><a href="/index/?page={{ book_list.next_page_number }}">下一页</a></li>
                 {% else %}
                    <li class="next disabled"><a href="#">下一页</a></li>
                 {% endif %}

            </ul>
</div>



</body>
</html>

扩展

核心逻辑

'''
    显示左5,右5,总共11个页,
    1 如果总页码大于11
        1.1 if 当前页码减5小于1,要生成1到12的列表(顾头不顾尾,共11个页码)
            page_range=range(1,12)
        1.2 elif 当前页码+5大于总页码,生成当前页码减10,到当前页码加1的列表(顾头不顾尾,共11个页码)
            page_range=range(paginator.num_pages-10,paginator.num_pages+1)
        1.3 else 生成当前页码-5,到当前页码+6的列表
            page_range=range(current_page_num-5,current_page_num+6)
    2 其它情况,生成的列表就是pageinator的page_range
        page_range=paginator.page_range

    '''

使用案例:

视图层

def page_test(request):
    # book_list=[]
    # for i in range(100):
    #     book=Book(name='book%s'%i,price=10+i,pub_date='2018-09-18',publish_id=1)
    #     book_list.append(book)
    # Book.objects.bulk_create(book_list,10)
    book_list=Book.objects.all()
    # 生成paginator对象,传入书籍列表,每页10条数据
    paginator=Paginator(book_list,3)
    # 总页码数
    print(paginator.num_pages)
    # 页码列表
    print(paginator.page_range)
    # 总数据
    print(paginator.count)
    # 获取页面传来的页码
    current_page=int(request.GET.get('page',1))
    page_range=[]
    # 左5 右5

    # 获取页面传来的页码的page对象
    try:
        page=paginator.page(current_page)
        # print(page.has_next())            #是否有下一页
        # print(page.next_page_number())    #下一页的页码
        # print(page.has_previous())        #是否有上一页
        # print(page.previous_page_number()) #上一页的页码
        # 循环打印出当页对象
        for i in page:
            print(i)
    except Exception as e:
        current_page=1
        page = paginator.page(1)
    if paginator.num_pages>11:
        if current_page+5>paginator.num_pages:
            page_range=range(paginator.num_pages-10,paginator.num_pages+1)
        elif current_page-5<1:
            page_range=range(1,12)
        else:
            page_range=range(current_page-5,current_page+6)
    else:
        page_range=paginator.page_range



    return render(request,'page_test.html',locals())

模板层

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <title>Title</title>
</head>
<body>

<ul>

    {% for foo in page %}
        <li>{{ foo.name }}</li>

    {% endfor %}

</ul>
<nav aria-label="Page navigation">
    <ul class="pagination">
        {% if page.has_previous %}
            <li>
                <a href="/page_test/?page={{ page.previous_page_number }}" aria-label="Previous">
                    <span aria-hidden="true">上一页</span>
                </a>
            </li>
        {% else %}
            <li class="disabled">
                <a href="#" aria-label="Previous">
                    <span aria-hidden="true">上一页</span>
                </a>
            </li>
        {% endif %}

        {% for foo in page_range %}
            {% if current_page == foo %}
                <li class="active"><a href="/page_test/?page={{ foo }}">{{ foo }}</a></li>
            {% else %}
                <li><a href="/page_test/?page={{ foo }}">{{ foo }}</a></li>
            {% endif %}

        {% endfor %}
        {% if page.has_next %}
            <li>
                <a href="/page_test/?page={{ page.next_page_number }}" aria-label="Next">
                    <span aria-hidden="true">下一页</span>
                </a>
            </li>
        {% else %}
            <li class="disabled">
                <a href="#" aria-label="Next">
                    <span aria-hidden="true">下一页</span>
                </a>
            </li>

        {% endif %}

    </ul>
</nav>


</body>
</html>
文档更新时间: 2022-03-10 09:30   作者:李延召