主要内容:
1 分页:
views里的代码:
user = [{'name':'alex'+str(i), 'pwd': 'alexdsb'+ str(i)} for i in range(1, 302)] from utils.pagination import Pagination def user_list(request): pages = Pagination(request, len(user)) return render(request, 'user_list.html', { 'user_list': user[pages.start: pages.end], # 'page_num': range(start_page, end_page + 1 ), 'html_str':pages.show_li })
2 html中的代码段:
{# 分页 #} <nav aria-label="Page navigation"> <ul class="pagination"> {{ html_str }} </ul> </nav>
3 自定义一个类分页
from django.utils.safestring import mark_safe class Pagination: def __init__(self, request, total_num, line_num=10, max_page = 11 ): # 基本url self.base_url = request.path_info # 当前页码 # 获取当前的页数, 解决每一页设置相应的内容 try: self.current_page = int(request.GET.get('page', 1)) if self.current_page <= 0: self.current_page = 1 except Exception as e: self.current_page = 1 self.page_num, more = divmod(total_num, line_num) if more: self.page_num = self.page_num + 1 # 最多显示的页码数 self.max_page = max_page half_page = max_page//2 # 每页显示的数据条数 self.line_num = line_num # 数据总量 self.total_num = total_num # 当总页码数小于最大显示数, 显示总页码数 if self.page_num <= max_page: self.start_page = 1 self.end_page = self.page_num else: # 获取开始的页数, 当当前数据小于half-page时, 会出现复数的问题,所以加上if判断 if self.current_page<=half_page: self.start_page = 1 self.end_page = max_page elif self.current_page + half_page > self.page_num: self.end_page = self.page_num self.start_page = self.page_num - max_page else: self.start_page = self.current_page - half_page # 获得结束的页数 self.end_page = self.current_page + half_page # 获取起始数据: @property def start(self): return (self.current_page - 1)*self.line_num # 获取结束数据 @property def end(self): return (self.current_page + 1)*self.line_num @property def show_li(self): #存放li标签的列表 html_list = [] # 添加首页和尾页 first_li = '<li><a href="{}?page=1">首页</a></li>'.format(self.base_url) html_list.append(first_li) # 添加前和后 if self.current_page == 1: pre_li = '<li class="disabled"><a><<</a></li>' else: pre_li = '<li><a href="{1}?page={0}"><<</a></li>'.format(self.current_page - 1, self.base_url) html_list.append(pre_li) # 正常的分页内容 for num in range( self.start_page, self.end_page + 1): if self.current_page == num: li_html = '<li class="active"><a href="{1}?page={0}">{0}</a></li>'.format(num, self.base_url) else: li_html = '<li><a href="{1}?page={0}">{0}</a></li>'.format(num, self.base_url) html_list.append(li_html) if self.current_page == self.page_num: next_li = '<li class="disabled"><a>>></a></li>' else: next_li = '<li><a href="{1}?page={0}">>></a></li>'.format(self.current_page + 1, self.base_url) html_list.append(next_li) last_li = '<li><a href="{1}?page={0}">尾页</a></li>'.format(self.total_num, self.base_url) html_list.append(last_li) return mark_safe(''.join(html_list))