Under enhanced paging component Django framework

This article by article syncing pushed to blog garden, display layout may be wrong, please forgive me!

Description: Django framework built pagination , but it can only meet the needs of simple, difficult to implement complex functions.

Implementation code:

! # / usr / bin / env python3 
# - * - Coding: UTF-8 - * - 
__auth__ = 'Song Wei' 

from django.utils.safestring Import mark_safe 
from the Math Import ceil 

class Paginator: 
    '' 'custom paging function, support settings tab properties, show support pages, supported the retention of other GET parameters, positioning support elements after the page jump. 
    Related available properties as follows: 
        Start data acquisition start position 
        end the data acquisition end position 
        prvePage Previous Page 
        nextPage Next Page 
        maxPage total page 
        pvreCode previous display text 
        nextCode Next display text 
        attr tag attributes common acquired 
        current_attr obtaining this page tag attributes 
        html generate html tag used directly in the template language 
        bootstrap bootstrap directly pagination style need to import bootstrap 
        bootstrap_size only boostrap optional settings to take effect when the template lg (large), sm (small)
        After the position support paging jump positioned to html specified id at the 
    relevant following methods are available: 
        setattr (attr, current_attr = None, Inheritance = True) Sets the label property 
        '' ' 

    DEF the __init __ (Self, The totalCount, perPage, The currentPage =. 1, pagerNumRange = 0, argName = 'P', kwargs = {}): 
        '' 'the total number of data totalCount 
            perPage page shows the number 
            currentPage current page 
            intermediate pagerNumRange previous / next page display how many digital default (0) is not displayed 
            argName page transmission parameter name defaults to the GET P 
            kwargs GET complement other parameters are generally empty or directly into `` request.GET`` 
        '' ' 
        self.maxPage = ceil (the totalCount / perPage) 
        the try:  
            Self.currentPage = int(currentPage)
        the except: 
            self.currentPage. 1 =
        self.pagerNumRange = self._pager_num_range(pagerNumRange)
        self.argName = argName
        self.kwargs = ''
        for k,v in kwargs.items():
            if k != self.argName:
                self.kwargs += '%s=%s&' % (k,v)
        self.end = self.currentPage * perPage
        self.start = self.end - perPage
        self.prvePage = self.currentPage - 1 if self.currentPage >1 else 1
        self.nextPage = self.currentPage + 1 if self.currentPage < self.maxPage else self.maxPage
        self.pattern = '<a {attr}href="?{kwargs}{argname}={href}">{content}</a> '
        self.attr,self._current_attr = '',''
        self.bootstrap_size = ''
        = self.position '' 
        self.pvreCode, self.nextCode = '& laquo;', '& raquo;' 

    @Property 
    DEF current_attr (Self): 
        '' 'returns this page tag attributes' '' 
        IF self._current_attr: 
            return Self. _current_attr 
        the else: 
            return self.attr 

    DEF _pager_num_range (Self, pager_num_range): 
        '' 'page display list of page numbers' '' 
        IF pager_num_range == 0: 
            return [] 
        the else: 
            Start = int (self.currentPage - (pager_num_range -1) / 2) 
            End = int ((+ self.currentPage (pager_num_range -. 1) / 2)) 
            IF Start <. 1:
                end += 1 - start
                start = 1 
                IF End> self.maxPage: 
                    End = self.maxPage 
            IF End> self.maxPage: 
                Start - End = - self.maxPage 
                End = self.maxPage 
                IF Start <. 1: 
                    Start. 1 = 
        return Range (Start, End + 1) 

    DEF setattr (Self, attr, current_attr = None, inheritance = True): 
        '' 'set the tag attribute 
            attr ordinary tag attributes 
            current_attr set to the current page additional property 
            inheritance current page attributes are inherited generic label attribute' '' 
        Self. = attr '' 
        for K, V in attr.items (): 
            self.attr + = '% S = "% S"'% (K, V)
        if current_attr:
            self._current_attr = ''
            if inheritance:
                for k,v in attr.items():
                    if k in current_attr:
                        self._current_attr += '%s="%s" ' % (k, current_attr[k])
                    else:
                        self._current_attr += '%s="%s" ' % (k, v)
                for k in current_attr.keys() - attr.keys():
                    self._current_attr += '%s="%s" ' % (k, current_attr[k])
            else:
                for k,v in current_attr.items():
                    self._current_attr += '%s="%s" ' % (k,v is the) 
    def Are the html (are not self):

    property
        '''生成html'''
        pagelist = ''
        position = '#' + self.position if self.position else ''
        if self.currentPage > 1:
            pagelist = self.pattern.format(attr=self.attr,href=str(self.prvePage) + position,
                                           kwargs=self.kwargs,argname=self.argName,content=self.pvreCode)
        for r in self.pagerNumRange:
            if r == self.currentPage:
                pagelist += self.pattern.format(attr=self.current_attr, href=str(r) + position,
                                                kwargs=self.kwargs, argname=self.argName,content=r)
            else:
                pagelist += self.pattern.format(attr=self.attr,href=str(r) + position,
                                                kwargs=self.kwargs, argname=self.argName,content=r)
        if self.currentPage < self.maxPage:
            pagelist += self.pattern.format(attr=self.attr,href=str(self.nextPage) + position,
                                            kwargs=self.kwargs, argname=self.argName,content=self.nextCode)
        return mark_safe(pagelist)

    @property
    def bootstrap(self):
        '直接使用bootstrap样式'
        html = '''
        <nav aria-label="Page navigation">
          <ul class="pagination">
            {pages}
          </ul>
        </nav>
        '''
        Previous = '''
            <li {disable}>
              <a href="{prvePage}" aria-label="Previous">
                <span aria-hidden="true">%s</span>
              </a>
            </li>
        ''' % self.pvreCode
        Next = '''
            <li {disable}>
              <a href="{nextPage}" aria-label="Next">
                <span aria-hidden="true">%s</span>
              </a>
            </li>
        ''' % self.nextCode
        pagelist = ''
        position = '#' + self.position if self.position else ''
        for r in self.pagerNumRange:
            if r == self.currentPage:
                pagelist += '<li class="active"><a href="?%s%s=%s%s">%s<span class="sr-only">(current)</span></a></li>' % (self.kwargs,self.argname,r,position, r)
            else:
                pagelist += '<li><a href="?%s%s=%s%s">%s</a></li>' % (self.kwargs,self.argName,r,position,r)
        if self.bootstrap_size in ('lg','sm'):
            html = html.replace('pagination','pagination pagination-%s' % self.bootstrap_size)
        if self.currentPage > 1:
            Previous = Previous.format(prvePage='?%s%s=%s' % (self.kwargs,self.argName,self.prvePage) + position,disable='')
        else:
            Previous = Previous.format(prvePage='#', disable='class="disabled"')
        if self.currentPage < self.maxPage:
            Next = Next.format(nextPage='?%s%s=%s' % (self.kwargs,self.argName,self.nextPage) + position,disable='')
        else:
            Next = Next.format(nextPage='#', disable='class="disabled"')
        return mark_safe(html.format(pages=Previous+pagelist+Next))

Call Example:

In the views .py in

page = Paginator(len(USER_LIST),15,p,7,'p',request.GET)

page.setattr(attr={'class':'btn btn-default'}, current_attr={'class':'btn btn-default active'})

page.size = 'lg'

return render(request,'web/index.html', {'PAGE':page, 'USER_LIST':USER_LIST[page.start:page.end]})

In the template tempaltes

{{ PAGE.html }} 或者 {{ PAGE.bootstrap }}

bootstrap bootstrap is used directly pagination style, without too much set, and html method is by setting Paginator property, etc., flexible.

Guess you like

Origin www.cnblogs.com/lazyfish007/p/11487542.html