django自定义分页器

分页器原理

自定义分页器需要掌握的基本思路

1.queryset对象是直接切片操作的

2.用户要访问的页码通过url后面携带参数传给后端		
	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.当前数据的总条数
	all_count = 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的情况,你需要做处理,不能再减

前端页面

<nav aria-label="Page navigation">
    <ul class="pagination">
        <li>
            <a href="#" aria-label="Previous">
            	<span aria-hidden="true">&laquo;</span>
            </a>
        </li>
        	{{ page_html|safe }}	
        <li>
            <a href="#" aria-label="Next">
            	<span aria-hidden="true">&raquo;</span>
            </a>
        </li>
    </ul>
 </nav>

后端分页逻辑

def page(request):

    current_page = request.GET.get('page', 1)
    try:
        current_page = int(current_page)
    except Exception:
        current_page = 1
    counts_per_page = 5	
    start_index = (current_page - 1) * counts_per_page
    end_index = current_page * counts_per_page

    total_user = models.User.objects.count()
    total_page_counts, more = divmod(total_user, counts_per_page)
    if more:
        total_page_counts += 1

    if current_page < 6:
        page_start = 6
    else:
        page_start = current_page

    page_html = ''
    for i in range(page_start - 5, current_page + 6):

        if i== int(current_page):
            page_html += f'<li class="active"><a href="?page={i}">{i}</a></li>'
        else:
            page_html += f'<li class=""><a href="?page={i}">{i}</a></li>'

    user_list = models.User.objects.all()[start_index:end_index]

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

自定义分页器

当我们需要使用到非django内置的第三方功能或者组件代码的时候,一般情况下会创建一个名为utils文件夹。

文件夹内存放第三方组件代码,utils可以在每个应用下创建也可以在项目根路径下,具体结合实际情况。

我们自定义的分页器是基于bootstrap样式来的,所以使用时需要提前导入bootstrap。

自定义分页器代码:utils/mypagination.py

class Pagination(object):
    def __init__(self, current_page, all_count, per_page_num=10, pager_count=11):
        """
        封装分页相关数据
        :param current_page: 当前页码,str
        :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('''
                                           </nav>
                                           </ul>
                                       ''')
        return ''.join(page_html_list)

使用方法

  • 拷贝上述代码存放在制定文件夹内,如utils

  • 后端引入该文件中的Pagination类并实例化对象

def page(request):
    book_queryset = models.Book.objects.all()
    current_page = request.GET.get('page',1)
    all_count = book_queryset.count()
    
    # 1 传值实例化对象
    page_obj = Pagination(current_page=current_page, all_count=all_count)
    # 2 直接对总数据进行切片操作
    page_queryset = book_queryset[page_obj.start:page_obj.end]
    # 3 将page_queryset传递到页面,替换之前的book_queryset
    return render(request, 'page.html', locals())
  • 前端页面,因为直接在后端书写了bootstrap的分页样式代码,前端直接safe显示该html即可。
{#数据展示部分#}
{% for book_obj in page_queryset %}
    <p>{{ book_obj.title }}</p>
{% endfor %}


{#分页器#}
{{ page_obj.page_html|safe }}

django分页器组件(参考)

views.py

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):


    '''
    分页器的使用:

    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})

index.html:

<!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>

扩展

def index(request):

    book_list=Book.objects.all()
    paginator = Paginator(book_list, 15)
    page = request.GET.get('page',1)
    currentPage=int(page)

    #  如果页数十分多时,换另外一种显示方式
    if paginator.num_pages>11:
        if currentPage-5<1:
            pageRange=range(1,11)
        elif currentPage+5>paginator.num_pages:
            pageRange=range(currentPage-5,paginator.num_pages+1)
        else:
            pageRange=range(currentPage-5,currentPage+5)
    else:
        pageRange=paginator.page_range
    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",locals())
posted @ 2020-06-04 19:15  the3times  阅读(178)  评论(0编辑  收藏  举报