• Django内置分页器与自定义分页器


    Django内置分页器

    views.py

    def index(request):
    
        # for i in range(300):
        #     name = "zekai%s" % (i)
        #     models.UserInfo.objects.create(name=name)
        try:
            cur_page = request.GET.get('cur_page') # 10 dfsadsa
            cur_page = int(cur_page)
        except Exception as e:
            cur_page = 1
    
    
        user_list = models.UserInfo.objects.all()
        ### 内置分页
    
        # per_page: 每页显示条目数量
        # count:    数据总个数
        # num_pages:总页数
        # page_range:总页数的索引范围,如: (1,10),(1,200)
        # page:     page对象
        paginator = Paginator(user_list, 10)
        # print(paginator.per_page, paginator.count, paginator.num_pages)
        users = paginator.page(cur_page)
        # has_next              是否有下一页
        # next_page_number      下一页页码
        # has_previous          是否有上一页
        # previous_page_number  上一页页码
        # object_list           分页之后的数据列表
        # number                当前页
        # paginator             paginator对象
        return render(request, "index.html", {"user_list":users})
    

    xxx.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Title</title>
    </head>
    <body>
        <ul>
            {% for user in user_list.object_list %}
                <li>{{ user.name }}</li>
            {% endfor %}
        </ul>
    
        {% if user_list.has_previous %}
            <a href="/index/?cur_page={{ user_list.previous_page_number }}">上一页</a>
        {% endif %}
    
        {% for num in user_list.paginator.page_range %}
            {% if num == user_list.number %}
                <a style="display: inline-block; padding: 5px; margin: 5px;background-color: red" href="/index/?cur_page={{ num }}">{{ num }}</a>
            {% else %}
                 <a style="display: inline-block; padding: 5px; margin: 5px;" href="/index/?cur_page={{ num }}">{{ num }}</a>
            {% endif %}
        {% endfor %}
    
        {% if user_list.has_next %}
            <a href="/index/?cur_page={{ user_list.next_page_number }}">下一页</a>
        {% endif %}
    
    </body>
    </html>
    

    自定义分页器

    尚泽恺views.py
    可更改custom来将数据提交到不同的页面上

    ###自定制的分页类
    class PageInfo():
        def __init__(self, cur_page, total, per_page=10, show_page=11):
            try:
                self.cur_page = int(cur_page)
            except  Exception as e:
                self.cur_page = 1
    
            self.per_page = per_page
            self.show_page = show_page
    
            a, b = divmod(total, per_page)
            if b:
                self.total_page = a + 1
            else:
                self.total_page = a
    
        def get_start(self):
            return (self.cur_page - 1) * self.per_page
    
        def get_stop(self):
            return  self.cur_page * self.per_page
    
        def page(self):
    
            half = int((self.show_page ) / 2)
    
    
            ### 总页数 < show_page  == 11
            if self.total_page < self.show_page:
                begin = 1
                stop = self.total_page + 1
            else:
                ### 总页数 > show_page  == 11
                if self.cur_page - 1 < half:
                    begin = 1
                    stop = self.show_page + 1
                elif self.cur_page + half > self.total_page:
                    # begin = self.cur_page  - half
                    begin = self.total_page - self.show_page + 1
                    stop = self.total_page + 1
                else:
                    begin = self.cur_page - half
                    stop = self.cur_page  + half + 1
    
            sli = []
            if self.cur_page == 1:
                # s =  "<a  style='display: inline-block; padding: 5px; margin: 5px;' href='#'>上一页</a>"
                s =  "<li class='disabled'><a href='#'>上一页</a></li>"
            else:
                # s =  "<li><a  style='display: inline-block; padding: 5px; margin: 5px;' href='/custom/?cur_page=%s'>上一页</a>" %(self.cur_page - 1)
                s =  "<li><a   href='/custom/?cur_page=%s'>上一页</a></li>" %(self.cur_page - 1)
    
            sli.append(s)
    
            for num in range(begin, stop):
                if num == self.cur_page:
                    # s = "<a  style='display: inline-block; padding: 5px; margin: 5px;background-color: red' href='/custom/?cur_page=%s'>%s</a>" %(num, num)
                    s = "<li class='active'><a   href='/custom/?cur_page=%s'>%s</a></li>" %(num, num)
                else:
                    # s = "<a  style='display: inline-block; padding: 5px; margin: 5px;' href='/custom/?cur_page=%s'>%s</a>" %(num, num)
                    s = "<li><a   href='/custom/?cur_page=%s'>%s</a></li>" %(num, num)
                sli.append(s)
    
            if self.cur_page == self.total_page:
                # s = "<a  style='display: inline-block; padding: 5px; margin: 5px;' href='#'>下一页</a>"
                s = "<li  class='disabled'><a  href='#'>下一页</a></li>"
            else:
                # s = "<a  style='display: inline-block; padding: 5px; margin: 5px;' href='/custom/?cur_page=%s'>下一页</a>" % (self.cur_page + 1)
                s = "<li><a  href='/custom/?cur_page=%s'>下一页</a></li>" % (self.cur_page + 1)
            sli.append(s)
    
            page_str = " ".join(sli)
    
            return page_str
    
    
    ### 自定制分页
    def custom(request):
    
        cur_page = request.GET.get('cur_page')  ## 字符串类型
    
        total = models.UserInfo.objects.count() # 301
        pageinfo = PageInfo(cur_page, total)
        # cur_page    start    stop
        #     1         0       10
        #     2         10      20
        #     3         20      30
        #     n        (n-1)*per_page   n * per_page
        start = pageinfo.get_start()
        stop = pageinfo.get_stop()
        user_list = models.UserInfo.objects.all()[start:stop]
    
        return render(request, "custom.html",{"user_list":user_list, "pageinfo":pageinfo})
    

    xxx.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Title</title>
        <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    </head>
    <body>
        <ul>
            {% for user in user_list %}
    
                <li>{{ user.name }}</li>
            {% endfor %}
        </ul>
    
    
    
        <nav aria-label="Page navigation">
          <ul class="pagination">
            {{ pageinfo.page | safe }}
          </ul>
    </nav>
    </body>
    </html>
    

    json/views.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:  最多显示的页码个数
    
            用法:
            queryset = model.objects.all()
            page_obj = Pagination(current_page,all_count)
            page_data = queryset[page_obj.start:page_obj.end]
            获取数据用page_data而不再使用原始的queryset
            获取前端分页样式用page_obj.page_html
            """
            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('''
                                               </nav>
                                               </ul>
                                           ''')
            return ''.join(page_html_list)
    
    def booklist(request):
        book_list = models.Book2.objects.all()
        all_count = book_list.count()
        current_page = request.GET.get('page',1)
        page_obj = my_page.Pagination(current_page=current_page,all_count=all_count)
        page_queryset = book_list[page_obj.start:page_obj.end]
        return render(request,'booklist.html',locals())
    
    

    json/.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
       <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <table class="table table-hover table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>id</th>
                            <th>name</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for book in page_queryset %}
                        <tr>
                            <td>{{ book.pk }}</td>
                            <td>{{ book.name }}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
                {{ page_obj.page_html|safe }}
            </div>
        </div>
    </div>
    </body>
    </html>
    
  • 相关阅读:
    Vue中computed和watch的区别
    JS基础语法
    JDBC
    表设计
    查询语句
    反射
    网络端
    多线程
    HashMap
    IO
  • 原文地址:https://www.cnblogs.com/huanghongzheng/p/11202022.html
Copyright © 2020-2023  润新知