django 分页处理


import re
from django.core.paginator import Paginator, InvalidPage
from django.db.models.query import QuerySet
from django.utils.translation import ugettext_lazy as _
import math

class Page(object):
    def __init__(self, queryset, request=None, pageno=1, paginate_by=20, urlprefix=None,urlnames=urlnames):
        if isinstance(queryset, QuerySet):
            self.queryset = queryset
        else:
            self.queryset = QuerysetWrapper(queryset)
        self.paginate_by = paginate_by
        self.request = request
        if urlprefix == None and request:
            newurl = re.sub(r'page=\d*', '', self.request.get_full_path())
            self.urlprefix = newurl
        else:
            self.urlprefix = urlprefix
        self.urlname = urlnames
        self.pageno = pageno
        
        paginator = Paginator(self.queryset, paginate_by)
        
        lastpage = math.ceil(1.0*paginator.count/paginate_by)
        
        if self.request and not pageno:
            try:
                page = self.request.GET['page']
            except:
                try:
                    page = self.request.POST.get('page','1')
                except:
                    page = self.pageno
        else:
            page = self.pageno
        try:
            if isinstance(page, str):
                if not page.isdigit():
                    page = 'last'
                    page = lastpage
            page = int(page)
            if page > lastpage:
                page = lastpage
                
            object_list = paginator.page(page).object_list
        except (InvalidPage, ValueError):
            object_list = []
        self.is_paginated = paginator.count > 1
        self.results_per_page = paginate_by
        try:
            self.has_next = paginator.page(page).has_next()
            self.has_previous = paginator.page(page).has_previous()
        except:
            self.has_next = False
            self.has_previous = False
        
        self.page = page
        self.next = page + 1
        self.previous = page - 1
        self.pages = paginator.count
        self.hits = paginator.num_pages
        self.object_list = object_list
        
        
    def next_url(self):
        if self.has_next:
            return '<a href="%spage=%d">%s</a>' % (self.fix_url(self.urlprefix), self.next, self.urlname['next'])
        return ''
        
    def previous_url(self):
        if self.has_previous:
            return '<a href="%spage=%d">%s</a>' % (self.fix_url(self.urlprefix), self.previous, self.urlname['previous'])
        else:
            return ''
        
    def first_url(self):
        if self.pages > 1:
            return '<a href="%spage=1">%s</a>' % (self.fix_url(self.urlprefix), self.urlname['first'])
        else:
            return ''
    
    def last_url(self):
        if self.pages > 1:
            return '<a href="%spage=%d">%s</a>' % (self.fix_url(self.urlprefix), self.pages, self.urlname['last'])
        else:
            return ''
        
    def fix_url(self, url):
        if url.find('?') == -1:
            url = url + '?'
        else:
            if not url.endswith('&') and not url.endswith('?'):
                url = url + '&'
        return url
    
    def page_url(self):
        """
        create page link url 
        exmple: <div><a href="group?page=2">2</a></div>
        """
        start_num = 1
        end_num = 1
        page_url = u''
        page_pre = u''
        page_last = u''
        #总页数小于等于显示分页数
        if self.hits <= 10:
            end_num = self.hits
         
        if self.hits > 10:
            if self.page-8 >=0:
                page_pre = u'<a href="%(href)spage=1">1</a><a href="%(href)spage=2">2</a>...' % {'href':self.fix_url(self.urlprefix)}
                start_num = self.page - 3
            if self.page+6 <= self.hits:
                page_last = u'..<a href="%(href)spage=%(self.page_pre)d">%(self.page_pre)d</a><a href="%(href)spage=%(self.page)d">%(self.page)d</a>' % {'href':self.fix_url(self.urlprefix),'self.page_pre':self.hits-1,'self.page':self.hits}
                
                if page_pre:
                    end_num = self.page + 3
                       
                else:
                    end_num = 8
            else:
                
                end_num = self.hits
                #start_num = self.page - 8
        page_url += page_pre   
        for n in range(start_num, end_num+1):
            if n == self.page:
                page_url += u'<a href="%(href)spage=%(self.page)d" class="current">%(self.page)d</a>' % {'href':self.fix_url(self.urlprefix),'self.page':n}    
            else:
                page_url += u'<a href="%(href)spage=%(self.page)d">%(self.page)d</a>' % {'href':self.fix_url(self.urlprefix),'self.page':n}     
        
        #设置上一页
        if self.page >1:
            page_url = u'<a href="%(href)spage=%(self.page)d">上一页</a>' % {'href':self.fix_url(self.urlprefix),'self.page':self.page-1} + page_url   
        if self.page < self.hits:
            page_last += u'<a href="%(href)spage=%(self.page)d">下一页</a>' % {'href':self.fix_url(self.urlprefix),'self.page':self.page+1}     
        page_url = u'<div class=page_list>'+ page_url + page_last + '</div>'
        if self.hits <=1:
            return ''
        return page_url
    
    def english_page_url(self):
        """
        create page link url 
        exmple: <div><a href="group?page=2">2</a></div>
        """
        start_num = 1
        end_num = 1
        page_url = u''
        page_pre = u''
        page_last = u''
        #总页数小于等于显示分页数
        if self.hits <= 10:
            end_num = self.hits
         
        if self.hits > 10:
            if self.page-8 >=0:
                page_pre = u'<li><a href="%(href)spage=1">1</a></li><li><a href="%(href)spage=2">2</a></li><li>...</li>' % {'href':self.fix_url(self.urlprefix)}
                start_num = self.page - 3
            if self.page+6 <= self.hits:
                page_last = u'<li>...</li><li><a href="%(href)spage=%(self.page_pre)d">%(self.page_pre)d</a></li><li><a href="%(href)spage=%(self.page)d">%(self.page)d</a></li>' % {'href':self.fix_url(self.urlprefix),'self.page_pre':self.hits-1,'self.page':self.hits}
                
                if page_pre:
                    end_num = self.page + 3
                       
                else:
                    end_num = 8
            else:
                
                end_num = self.hits
                #start_num = self.page - 8
        page_url += page_pre   
        for n in range(start_num, end_num+1):
            if n == self.page:
                page_url += u'<li class=on><a href="%(href)spage=%(self.page)d">%(self.page)d</a></li>' % {'href':self.fix_url(self.urlprefix),'self.page':n}    
            else:
                page_url += u'<li><a href="%(href)spage=%(self.page)d">%(self.page)d</a></li>' % {'href':self.fix_url(self.urlprefix),'self.page':n}     
        
        #设置上一页
        if self.page >1:
            page_url = u'<li ><a href="%(href)spage=%(self.page)d">Prev</a></li>' % {'href':self.fix_url(self.urlprefix),'self.page':self.page-1} + page_url   
        if self.page < self.hits:
            page_last += u'<li ><a href="%(href)spage=%(self.page)d">Next</a></li>' % {'href':self.fix_url(self.urlprefix),'self.page':self.page+1}     
        page_url = u'<div class="jx_page1"><ul>'+ page_url + page_last + '</ul></div>'
        if self.hits <=1:
            return ''
        return page_url

    def english_page_ajax_url(self,action='list'):
        """
        create page link url 
        exmple: <div><a href="group?page=2">2</a></div>
        """
        start_num = 1
        end_num = 1
        page_url = u''
        page_pre = u''
        page_last = u''
        #总页数小于等于显示分页数
        if self.hits <= 10:
            end_num = self.hits
         
        if self.hits > 10:
            if self.page-8 >=0:
                page_pre = u'<li><a οnclick="go(\'%(action)s\',1)" href="javascript:void(0)">1</a></li><li><a οnclick="go(\'%(action)s\',2)" href="javascript:void(0)">2</a></li><li>...</li>' % {'action':action}
                start_num = self.page - 3
            if self.page+6 <= self.hits:
                page_last = u'<li>...</li><li><a οnclick="go(\'%(action)s\',%(self.page_pre)d)" href="javascript:void(0)">%(self.page_pre)d</a></li><li><a οnclick="go(\'%(action)s\',%(self.page)d)" href="javascript:void(0)">%(self.page)d</a></li>' % {'action':action,'self.page_pre':self.hits-1,'self.page':self.hits}
                
                if page_pre:
                    end_num = self.page + 3
                       
                else:
                    end_num = 8
            else:
                
                end_num = self.hits
                #start_num = self.page - 8
        page_url += page_pre   
        for n in range(start_num, end_num+1):
            if n == self.page:
                page_url += u'<li class="on"><a οnclick="go(\'%(action)s\',%(self.page)d)" href="javascript:void(0)">%(self.page)d</a></li>' % {'action':action,'self.page':n}    
            else:
                page_url += u'<li><a οnclick="go(\'%(action)s\',%(self.page)d)" href="javascript:void(0)">%(self.page)d</a></li>' % {'action':action,'self.page':n}     
        
        #设置上一页
        if self.page >1:
            page_url = u'<li><a οnclick="go(\'%(action)s\',%(self.page)d)" href="javascript:void(0)">Prev</a></li>' % {'action':action,'self.page':self.page-1} + page_url   
        if self.page < self.hits:
            page_last += u'<li><a οnclick="go(\'%(action)s\',%(self.page)d)" href="javascript:void(0)">Next</a></li>' % {'action':action,'self.page':self.page+1}     
        page_url = u'<div class="jx_page1"><ul>'+ page_url + page_last + '</ul></div>'
        if self.hits <=1:
            return ''
        return page_url
    
    def page_ajax_url(self, action='list'):
            """
            create page link url 
            exmple: <div><a href="group?page=2">2</a></div>
            <a οnclick="go(\'%(action)s\',3)" href="javascript:void(0)">3</a>
            """
            start_num = 1
            end_num = 1
            page_url = u''
            page_pre = u''
            page_last = u''
            #总页数小于等于显示分页数
            if self.hits <= 10:
                end_num = self.hits
             
            if self.hits > 10:
                if self.page-8 >=0:
                    page_pre = u'<a οnclick="go(\'%(action)s\',1)" href="javascript:void(0)">1</a><a οnclick="go(\'%(action)s\',2)" href="javascript:void(0)">2</a>...' % {'action':action}
                    start_num = self.page - 3
                if self.page+6 <= self.hits:
                    page_last = u'..<a οnclick="go(\'%(action)s\',%(self.page_pre)d)" href="javascript:void(0)">%(self.page_pre)d</a><a οnclick="go(\'%(action)s\',%(self.page)d)" href="javascript:void(0)">%(self.page)d</a>' % {'action':action,'self.page_pre':self.hits-1,'self.page':self.hits}
                    
                    if page_pre:
                        end_num = self.page + 3
                           
                    else:
                        end_num = 8
                else:
                    
                    end_num = self.hits
                    #start_num = self.page - 8
            page_url += page_pre
            for n in range(start_num, int(end_num)+1):
                if n == self.page:
                    page_url += u'<a οnclick="go(\'%(action)s\',%(self.page)d)" href="javascript:void(0)" class="current">%(self.page)d</a>' % {'action':action,'self.page':n}    
                else:
                    page_url += u'<a οnclick="go(\'%(action)s\',%(self.page)d)" href="javascript:void(0)">%(self.page)d</a>' % {'action':action,'self.page':n}     
            
            # 设置上一页
            if self.page >1:
                page_url = u'<a οnclick="go(\'%(action)s\',%(self.page)d)" href="javascript:void(0)">上一页</a>' % {'action':action,'self.page':self.page-1} + page_url   
            if self.page < self.hits:
                page_last += u'<a οnclick="go(\'%(action)s\',%(self.page)d)" href="javascript:void(0)">下一页</a>' % {'action':action,'self.page':self.page+1}     
            page_url = u'<div class=page_list>'+ page_url + page_last + '</div>'
            if self.hits <=1:
                return ''
            return page_url   
Django处理分页主要通过Paginator类来实现,具体步骤如下: 1. **导入Paginator**: 首先,需要在视图文件中导入Paginator类。 ```python from django.core.paginator import Paginator ``` 2. **创建Paginator对象**: 使用查询集(如数据库中的条目)和每页显示的条目数来实例化Paginator对象。 ```python paginator = Paginator(queryset, items_per_page) ``` 其中`queryset`是从数据库中获取的数据集合,`items_per_page`是每页显示的条目数量。 3. **获取页码**: 从请求中获取当前页码,通常通过GET参数传递。 ```python page_number = request.GET.get('page') ``` 4. **获取分页后的数据**: 使用Paginator对象的`get_page`方法获取特定页的数据。 ```python try: page = paginator.get_page(page_number) except PageNotAnInteger: # 如果页码不是整数,显示第一页 page = paginator.get_page(1) except EmptyPage: # 如果页码超出范围,显示最后一页 page = paginator.page(paginator.num_pages) ``` 5. **渲染到模板**: 将分页后的数据传递给模板进行渲染。 ```python return render(request, 'template_name.html', {'page': page}) ``` 6. **在模板中显示分页信息**: 使用`page`对象的属性如`has_previous`, `previous_page_number`, `has_next`, `next_page_number`等来显示分页导航。 ```html {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">上一页</a> {% endif %} <span class="current"> 第{{ page.number }}页 / 共{{ page.paginator.num_pages }}页 </span> {% if page.has_next %} <a href="?page={{ page.next_page_number }}">下一页</a> {% endif %} ``` 通过这些步骤,可以在Django项目中实现基本的分页功能。分页不仅提高了用户体验,还减轻了服务器的负载。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值