分頁框架

views代碼:

class PageInfo:
    def __init__(self, page_num, per_page, all_data, base_page):
        '''
        :param page_num: 當前頁
        :param per_page: 每頁數據數量
        :param all_data: 總數據量
        :param base_page: 固定頁數
       '''
        try:
            self.page_num = int(page_num)
        except Exception as e:
            self.page_num = 1
            self.per_page = int(per_page)
            self.all_data = all_data
            self.base_page = base_page

    def start(self):
        return (self.page_num - 1) * self.per_page

    def end(self):
        return self.page_num * self.per_page

    # 總頁數函數(總數據/每頁條數)
    def total_pages(self):
        a, b = divmod(self.all_data, self.per_page)
        if b:
            a = a + 1
        return a

    def pager(self):
        page_list = []
        harf = divmod(self.base_page, 2)[0]
        # 若是總頁數小於固定分頁
        if self.total_pages() <= self.base_page:
            begin = 1
            end = self.total_pages()
        # 若是當前頁 + 固定頁的一半大於總頁數
        elif self.page_num + harf >= self.total_pages():
            begin = self.total_pages() - self.base_page + 1
            end = self.total_pages()
    # 若是當前頁小於harf+1
        elif self.page_num < harf + 1:
            begin = 1
            end = self.base_page
        else:
            begin = self.page_num - harf
            end = self.page_num + harf
    # 上一頁
        if self.page_num <= 1:
            prev = '<li><a href="#">上一頁</a></li>'
        else:
            prev = '<li><a href="?p=%s">上一頁</a></li>' % (self.page_num - 1)
        page_list.append(prev)

        for i in range(begin, end + 1):
            if i == self.page_num:
                temp = '<li class="active"><a href="?p=%s">%s</a></li>' % (i, i)
            else:
                temp = '<li><a href="?p=%s">%s</a></li>' % (i, i)
            page_list.append(temp)
    # 下一頁
        if self.page_num >= self.total_pages():
            prev = '<li><a href="#">下一頁</a></li>'
        else:
            prev = '<li><a href="?p=%s">下一頁</a></li>' % (self.page_num + 1)
            page_list.append(prev)
        return page_list
        
        
def custom(request):
    page_num = request.GET.get('p') #當前頁
    all_page = models.UserInfo.objects.all().count()
    # 實例化一個page_info對象
    page_info = PageInfo(page_num,10,all_page,11)
    user_list = models.UserInfo.objects.all()[page_info.start():page_info.end()]
    return render(request,'custom.html',{'user_list':user_list,'page_list':page_info.pager()})

 


 

 

 

HTML代碼:

<label for="">
  #顯示分頁內容
     {% for row in user_list %} <li>{{ row.id }},{{ row.name }},{{ row.age }}</li> {% endfor %}
  #分頁欄
<nav aria-label="Page navigation"> <ul class="pagination"> {% for page in page_list %} {{ page |safe }} {% endfor %} </ul> </nav> </label>
相關文章
相關標籤/搜索