Django自定制插件之【分页组件】

Django内置分页 Paginator

- Django内置分页
- Paginator、 Page
- 单写分页页面:用include续加到所需页面

view.py

from django.shortcuts import render

# Create your views here.
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
USER_LIST=[]
for i in range(999):
    temp={'name':'root'+str(i),'age':i}
    USER_LIST.append(temp)
def fenye(request):
    current_page=request.GET.get('p')
    paginator=Paginator(USER_LIST,10)
    try:
        posts = paginator.page(current_page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)
    return render(request, 'fenye.html', {'posts': posts})

fenye.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul>
    {% for item in posts.object_list %}
        <li>{{ item.name }}-{{ item.age }}</li>
    {% endfor %}
</ul>
{% if posts.has_previous %}
    <a href="fenye?p={{ posts.previous_page_number }}">上一页</a>
{% else %}
    <a href="#">上一页</a>
{% endif %}

{% if posts.has_next %}
    <a href="/fenye?p={{ posts.next_page_number }}">下一页</a>
{% else %}
    <a href="#">下一页</a>
{% endif %}
<span>
    {{ posts.number }}|{{ posts.paginator.num_pages }}
</span>

</body>
</html>

但是只用Django 自带的Paginator功能只能实现【上一页】【下一页】1/100   此类效果不能实现中间有页码显示

扩展Django的内置分页

继承定义类CustomPaginator
- CustomPaginator(Paginator)
传入(需求):
- 所有数据
- 当前页
- 每页显示10条
- 最多页面7个

view.py

from django.shortcuts import render

# Create your views here.
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
USER_LIST=[]
for i in range(999):
    temp={'name':'root'+str(i),'age':i}
    USER_LIST.append(temp)


class CustomPaginator(Paginator):
    def __init__(self,current_page,per_pager_num,*args,**kwargs):
        #当前页
        self.current_page=int(current_page)
        #最多显示的页码数量
        self.per_pager_num=int(per_pager_num)
        super(CustomPaginator,self).__init__(*args,**kwargs)
    def pager_num_range(self):
        if self.num_pages<self.per_pager_num:
            return range(1,self.num_pages+1)
        #如果页数特别多
        part=int(self.per_pager_num/2)
        if self.current_page<=part:
            return range(1,self.per_pager_num+1)
        if (self.current_page+part)>self.num_pages:
            return range(self.num_pages-self.per_pager_num+1,self.num_pages+1)
        return range(self.current_page - part, self.current_page + part + 1)


def index(request):
    current_page = request.GET.get('p')

    paginator = CustomPaginator(current_page, 7, USER_LIST, 10)

    try:
        posts = paginator.page(current_page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)
    return render(request, 'index.html', {'posts':posts})

index.py

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul>
    {% for item in posts.object_list %}
        <li>{{ item.name }}-{{ item.age }}</li>
    {% endfor %}
</ul>
{% include 'include/pager.html' %}

</body>
</html>

pager.py

{% if posts.has_previous %}
    <a href="index?p={{ posts.previous_page_number }}">上一页</a>
{% else %}
    <a href="#">上一页</a>
{% endif %}
{% for i in posts.paginator.pager_num_range %}
    {% if i == posts.number %}
        <a style="font-size: 20px" href="/index?p={{ i }}">{{ i }}</a>
    {% else %}
        <a href="/index?p={{ i }}">{{ i }}</a>
    {% endif %}
{% endfor %}
{% if posts.has_next %}
    <a href="/index?p={{ posts.next_page_number }}">下一页</a>
{% else %}
    <a href="#">下一页</a>
{% endif %}
<span>
    {{ posts.number }}|{{ posts.paginator.num_pages }}
</span>

此扩展能实现【上一页】1 2 3 4 5 6 7【下一页】1/100 效果,但这个扩展只能在Django框架中用。

自定制分页实现代码

class Pagination(object):
    def __init__(self,totalCount,currentPage,perPageItemNum=10,maxPageNum=7):
        # 数据总个数
        self.total_count = totalCount
        # 当前页
        try:
            v = int(currentPage)
            if v <= 0:
               v = 1
            self.current_page = v
        except Exception as e:
            self.current_page = 1
        # 每页显示的行数
        self.per_page_item_num = perPageItemNum
        # 最多显示页面
        self.max_page_num = maxPageNum

    def start(self):
        return (self.current_page-1) * self.per_page_item_num

    def end(self):
        return self.current_page * self.per_page_item_num
    @property
    def num_pages(self):
        """
        总页数
        :return:
        """
        # 666
        # 10
        a,b = divmod(self.total_count,self.per_page_item_num)
        if b == 0:
            return a
        return a+1

    def pager_num_range(self):
        # self.num_pages()
        # self.num_pages
        # 当前页
        #self.current_page
        # 最多显示的页码数量 11
        #self.per_pager_num
        # 总页数
        # self.num_pages
        if self.num_pages < self.max_page_num:
            return range(1,self.num_pages+1)
        # 总页数特别多 5
        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_str(self):
        page_list = []

        first = "<li><a href='/index2.html?p=1'>首页</a></li>"
        page_list.append(first)

        if self.current_page == 1:
            prev = "<li><a href='#'>上一页</a></li>"
        else:
            prev = "<li><a href='/index2.html?p=%s'>上一页</a></li>" %(self.current_page-1,)
        page_list.append(prev)
        for i in self.pager_num_range():
            if i == self.current_page:
                temp = "<li class='active'><a href='/index2.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:
            nex = "<li><a href='#'>下一页</a></li>"
        else:
            nex = "<li><a href='/index2.html?p=%s'>下一页</a></li>" % (self.current_page + 1,)
        page_list.append(nex)

        last = "<li><a href='/index2.html?p=%s'>尾页</a></li>" %(self.num_pages,)
        page_list.append(last)

        return ''.join(page_list)

补充:更灵活配置URL

__author__ = 'Administrator'
from django.utils.safestring import mark_safe


class Pagination(object):
	#所传参数更为灵活,只需传入current_page, data_count
    def __init__(self, current_page, data_count, per_page_count=10, pager_num=7):
        try:
            self.current_page = int(current_page)
        except Exception as e:
            self.current_page = 1
        self.data_count = data_count
        self.per_page_count = per_page_count
        self.pager_num = pager_num

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

    @property
    def end(self):
        return self.current_page * self.per_page_count

    @property
    def total_count(self):
        v, y = divmod(self.data_count, self.per_page_count)
        if y:
            v += 1
        return v
	#传入base_url
    def page_str(self, base_url):
        page_list = []

        if self.total_count < self.pager_num:
            start_index = 1
            end_index = self.total_count + 1
        else:
            if self.current_page <= (self.pager_num + 1) / 2:
                start_index = 1
                end_index = self.pager_num + 1
            else:
                start_index = self.current_page - (self.pager_num - 1) / 2
                end_index = self.current_page + (self.pager_num + 1) / 2
                if (self.current_page + (self.pager_num - 1) / 2) > self.total_count:
                    end_index = self.total_count + 1
                    start_index = self.total_count - self.pager_num + 1

        if self.current_page == 1:
            prev = '<li><a class="page" href="javascript:void(0);">上一页</a></li>'
        else:
            prev = '<li><a class="page" href="%s?p=%s">上一页</a></li>' % (base_url, self.current_page - 1,)
        page_list.append(prev)

        for i in range(int(start_index), int(end_index)):
            if i == self.current_page:
                temp = '<li class="active"><a class="page active" href="%s?p=%s">%s</a></li>' % (base_url, i, i)
            else:
                temp = '<li><a class="page" href="%s?p=%s">%s</a></li>' % (base_url, i, i)
            page_list.append(temp)

        if self.current_page == self.total_count:
            nex = '<li><a class="page" href="javascript:void(0);">下一页</a></li>'
        else:
            nex = '<li><a class="page" href="%s?p=%s">下一页</a></li>' % (base_url, self.current_page + 1,)
        page_list.append(nex)

        # jump = """
        # <input type='text'  /><a οnclick='jumpTo(this, "%s?p=");'>GO</a>
        # <script>
        #     function jumpTo(ths,base){
        #         var val = ths.previousSibling.value;
        #         location.href = base + val;
        #     }
        # </script>
        # """ % (base_url,)
        #
        # page_list.append(jump)

        page_str = mark_safe("".join(page_list))

        return page_str

  

 

转载于:https://www.cnblogs.com/mocean/p/6557806.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值