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})