• 分页


    一. Django内置分页

    1.django内置分页

    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 = Paginator(L, 10)
        #paginator对象所含方法
        # per_page: 每页显示条目数量
        # count:    数据总个数
        # num_pages:总页数
        # page_range:总页数的索引范围,如: (1,10),(1,200)
        # page:     page对象
        try:
           #page对象
            posts = paginator.page(current_page)
            #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})
    View Code
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>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 }}">上一页</a>
            {% else %}
                <a href="?p=1">上一页</a>
            {% endif %}
    
            {% if posts.has_next %}
                <a href="?p={{ posts.next_page_number }}">下一页</a>
            {% else %}
                <a href="?P={{ posts.paginator.num_pages }}">下一页</a>
              {% endif %}
          
            <span class="current">
               {{ posts.number }}/{{ posts.paginator.num_pages }}
            </span>
          </span>
    
    </div>
    
    </body>
    HTML

     2.扩展django内置分页

    from django.shortcuts import render
    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
    
    class CustomPaginator(Paginator):
        def __init__(self, current_page, max_pager_num, *args, **kwargs):
            """
            :param current_page: 当前页
            :param max_pager_num:最多显示的页码个数
            :param args:
            :param kwargs:
            :return:
            """
            self.current_page = int(current_page)
            self.max_pager_num = max_pager_num
            super(CustomPaginator, self).__init__(*args, **kwargs)
    
        def page_num_range(self):
            # 当前页面
            # self.current_page
            # 总页数
            # self.num_pages
            # 最多显示的页码个数
            # self.max_pager_num
            print(1)
            if self.num_pages < self.max_pager_num:
                return range(1, self.num_pages + 1)
            print(2)
            part = int(self.max_pager_num / 2)
            if self.current_page - part <= 1:
                return range(1, self.max_pager_num + 1)
            print(3)
            if self.current_page + part > self.num_pages:
                return range(self.num_pages + 1 - self.max_pager_num, self.num_pages + 1)
            print(4)
            return range(self.current_page - part, self.current_page + part + 1)
    L = []
    for i in range(999):
        L.append(i)
    def index(request):
        current_page = request.GET.get('p')
        #paginator对象
        paginator = CustomPaginator(current_page,7,L, 10)
        # per_page: 每页显示条目数量
        # count:    数据总个数
        # num_pages:总页数
        # page_range:总页数的索引范围,如: (1,10),(1,200)
        # page:     page对象
        try:
            #page对象
            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})
    View Code
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>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 }}">上一页</a>
            {% else %}
                <a href="?p=1">上一页</a>
            {% endif %}
    
            {% for i in posts.paginator.page_num_range %}
            <a href="?p={{ i }}">{{ i }}</a>
            {% endfor %}
    
    
            {% if posts.has_next %}
                <a href="?p={{ posts.next_page_number }}">下一页</a>
            {% else %}
                <a href="?P={{ posts.paginator.num_pages }}">下一页</a>
              {% endif %}
    
            <span class="current">
               {{ posts.number }}/{{ posts.paginator.num_pages }}
            </span>
          </span>
    
    </div>
    
    </body>
    HTML

     二. 自定制分页

     1.自定制分页设计步骤

     <1>设定每页显示数据条数

     <2>用户输入页码(第一页、第二页...)

     <3>设定显示多少页号

     <4>获取当前数据总条数

     <5>根据设定显示多少页号和数据总条数计算出,总页数

     <6>根据设定的每页显示条数和当前页码,计算出需要取数据表的起始位置

     <7>在数据表中根据起始位置取值,页面上输出数据

       <8>输出分页html,如:[上一页][1][2][3][4][5][下一页]

     2.自定制分页设计

    class Pagination(object):
        def __init__(self,TotalItemCount,CurrentPage,PerPageItemNum=10,MaxPageNum=7):
            """
            input parameter
            TotalItemCount:数据总个数
            current_page: 当前页
            PerPageItemNum:每页显示数据个数
            MaxPageNum:最多显示的页码个数
            :return:
            """
            self.total_item_count = TotalItemCount
            try:
                CurrentPage = int(CurrentPage)
                if CurrentPage <= 0:
                    CurrentPage = 1
                self.current_page = CurrentPage
            except Exception as e:
                self.current_page = 1
            self.per_page_item_num = int(PerPageItemNum)
            self.max_page_num =int(MaxPageNum)
        @property
        def start(self):
            """当前页开始数据索引"""
            return (self.current_page-1) * self.per_page_item_num
        @property
        def end(self):
            """当前页结束数据索引"""
            return self.current_page * self.per_page_item_num
        @property
        def num_pages(self):
            """计算总页数"""
            a,b = divmod(self.total_item_count,self.per_page_item_num)
            if b == 0:
                return a
            return a+1
    
        def page_num_range(self):
            """计算每页显示的页码"""
            if self.num_pages < self.max_page_num:
                return range(1,self.num_pages+1)
            part = int(self.max_page_num/2)
            if self.current_page <= part:
                return range(1,self.max_page_num+1)
            if (self.current_page + part) > self.num_pages:
                return range(self.num_pages-self.max_page_num+1,self.num_pages+1)
            return range(self.current_page-part,self.current_page+part+1)
    
        def page_html(self):
            """输出分页html"""
            page_list = []
            home_page = "<li><a href='/index.html?p=1'>首页</a></li>"
            page_list.append(home_page)
            if self.current_page == 1:
                previous_page = "<li><a href='#'>上一页</a></li>"
            else:
                previous_page = "<li><a href='/index.html?p=%s'>上一页</a></li>" %(self.current_page-1,)
            page_list.append( previous_page)
            for i in self.page_num_range():
                if i == self.current_page:
                    temp = "<li class='active'><a href='/index.html?p=%s'>%s</a></li>" %(i,i)
                else:
                    temp = "<li><a href='/index2.html?p=%s'>%s</a></li>" % (i, i)
                page_list.append(temp)
    
            if self.current_page == self.num_pages:
                next_page = "<li><a href='#'>下一页</a></li>"
            else:
                next_page = "<li><a href='/index.html?p=%s'>下一页</a></li>" % (self.current_page + 1,)
            page_list.append(next_page)
    
            last_page = "<li><a href='/index.html?p=%s'>尾页</a></li>" %(self.num_pages,)
            page_list.append(last_page)
            return ''.join(page_list)
    自定制Pagination类  
    from django.shortcuts import render
    from student_manage.views.pagination import *
    USER_LIST = []
    for i in range(1,666):
        temp = {'name':'root'+str(i), 'age':i}
        USER_LIST.append(temp)
    def index(request):
        current_page = request.GET.get('p')
        TotalItemCount=len(USER_LIST)
        print(TotalItemCount)
        paginator=Pagination(TotalItemCount,current_page,'10','11')
        data_list=USER_LIST[paginator.start:paginator.end]
        return render(request, 'index.html', {'data_list': data_list,'paginator':paginator})
    调用自定制类
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
         <link rel="stylesheet" href="/static/plugin/bootstrap/css/bootstrap.css" />
    </head>
    <body>
        <ul>
        {% for item in  data_list %}
            <li>{{item}}</li>
        {% endfor %}
        </ul>
        <ul class="pagination pagination-sm">
            {{ paginator.page_html|safe }}
        </ul>
    
    
    </body>
    </html>
    View Code

    >>>>>>待续

  • 相关阅读:
    移动端rem布局
    父子组件通信
    拦截器
    Vue路由教程
    使用var和let的区别
    数组去重的几种方法
    利用位运算进行权限控制
    线程基础
    关于get请求的乱码问题
    nuxt.js Navigating to current location ("/xxx") is not allowed
  • 原文地址:https://www.cnblogs.com/wuxunyan/p/9202969.html
Copyright © 2020-2023  润新知