1. 程式人生 > >Django的分頁器

Django的分頁器

一個分頁器的模板

import copy


class Pagination(object):

    def __init__(self, current_page_num, all_count, request, per_page_num, page_count=11):
        '''

        :param current_page_num:當前訪問頁的數字
        :param all_count:分頁資料中的資料總條數
        :param request:
        :param per_page_num:每頁顯示的資料條數
        :param page_count:最多顯示的頁碼個數
        
''' try: current_page_num = int(current_page_num) except Exception as e: current_page_num = 1 if current_page_num < 1: current_page_num = 1 self.current_page_num = current_page_num self.all_count = all_count self.per_page_num
= per_page_num self.page_count = page_count # 實際總頁碼,每頁顯示的資料條數 all_page, tmp = divmod(all_count, per_page_num) if tmp: all_page += 1 self.all_page = all_page self.page_count = page_count self.page_count_half = int((page_count - 1) / 2)
# 儲存搜尋條件 self.params = copy.deepcopy(request.GET) @property def start(self): return (self.current_page_num - 1) * self.per_page_num @property def end(self): return self.current_page_num * self.per_page_num def page_html(self): # 如果總頁碼<11個 if self.all_page <= self.page_count: page_start = 1 page_end = self.all_page + 1 # 如果總頁碼>11 else: # 如果當前頁<5 if self.current_page_num <= self.page_count_half: page_start = 1 page_end = self.page_count + 1 # 如果當前頁>5 else: # 頁碼翻到最後 # 如果當前頁+5>總頁數 if (self.current_page_num + self.page_count_half) > self.all_page: page_start = self.all_page - self.page_count + 1 page_end = self.all_page + 1 # (10,21) else: page_start = self.current_page_num - self.page_count_half page_end = self.current_page_num + self.page_count_half + 1 page_html_list = [] first_page = '<li><a href="?page=%s">首頁</a></li>' % 1 page_html_list.append(first_page) if self.current_page_num <= 1: prev_page = '<li class="disabled"><a href="#">上一頁</a></li>' else: prev_page = '<li><a href="?page=%s">上一頁</a></li>' % (self.current_page_num - 1) page_html_list.append(prev_page) for i in range(page_start, page_end): self.params["page"] = i if i == self.current_page_num: temp = '<li class="active"><a href="?%s">%s</a></li>' % (self.params.urlencode(), i) else: temp = '<li><a href="?%s">%s</a></li>' % (self.params.urlencode(), i) page_html_list.append(temp) if self.current_page_num >= self.all_page: next_page = '<li class="disabled"><a href="#">下一頁</a></li>' else: next_page = '<li><a href="?page=%s">下一頁</a></li>' % (self.current_page_num + 1) page_html_list.append(next_page) last_page = '<li><a href="?page=%s">尾頁</a></li>' % self.all_page page_html_list.append(last_page) return "".join(page_html_list)

在檢視函式中呼叫分頁器(部分程式碼):

from page import Pagination

def index(request):
    current_page_num = request.GET.get("page")    #獲取第幾頁
    all_count = data_list.count()    #獲取所有資料
    per_page_num = 10    #每頁顯示10條資料
    pagination = Pagination(current_page_num, all_count, request, per_page_num) 
    data_list = data_list[pagination.start:pagination.end]
    return render(request,"data.html", {"data_list":data_list})