django提供了分页函数,但是功能较少,因此我对其进行了扩展
views.py
1 from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
2 USER_LIST = []
3 for i in range(1,999):
4 temp = {'name':'root'+str(i),'age':i}
5 USER_LIST.append(temp)
6 #自定制的继承于Paginator的类,增加了显示页码功能
7 class CustomPaginator(Paginator):
8 def __init__(self,current_page, per_pager_num,*args,**kwargs):
9 # 当前页
10 self.current_page = int(current_page)
11 # 最多显示的页码数量 11
12 self.per_pager_num = int(per_pager_num)
13 super(CustomPaginator,self).__init__(*args,**kwargs)
14 def pager_num_range(self):
15 # 当前页
16 #self.current_page
17 # 最多显示的页码数量 11
18 #self.per_pager_num
19 # 总页数
20 # self.num_pages
21 if self.num_pages < self.per_pager_num:
22 return range(1,self.num_pages+1)
23 # 总页数特别多 5
24 part = int(self.per_pager_num/2)
25 if self.current_page <= part:
26 return range(1,self.per_pager_num+1)
27 if (self.current_page + part) > self.num_pages:
28 return range(self.num_pages-self.per_pager_num+1,self.num_pages+1)
29 return range(self.current_page-part,self.current_page+part+1)
30
31 def FenYe(request):
32
33 current_page = request.GET.get('p')
34 # Paginator对象
35 paginator = CustomPaginator(current_page,11,USER_LIST,10)#调用自定义类参数为(当前页码,显示的页码数,总的数据,每页显示的数据条数)
36 try:
37 # Page对象
38 posts = paginator.page(current_page)
39
40 except PageNotAnInteger:
41 posts = paginator.page(1)
42 except EmptyPage:
43 posts = paginator.page(paginator.num_pages)
44
45 return render(request, 'fenye.html', {'posts': posts})
fenye.html:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>fenye1</title> 6 </head> 7 <body> 8 {% for item in posts %} 9 <li>{{ item.name }}--{{ item.age }}</li> 10 {% endfor %} 11 {% include 'include/pager.html' %} 12 13 </body> 14 </html>
pager.html
1 {% if posts.has_previous %}
2 <a href="/fenye1?p={{ posts.previous_page_number }}">上一页</a>
3 {% else %}
4 <a href="#">上一页</a>
5 {% endif %}
6 {% for i in posts.paginator.pager_num_range %}
7 {% if i == posts.number %}
8 <a style="font-size: 30px;" href="/fenye1?p={{ i }}">{{ i }}</a>
9 {% else %}
10 <a href="/fenye1?p={{ i }}">{{ i }}</a>
11 {% endif %}
12 {% endfor %}
13
14 {% if posts.has_next %}
15 <a href="/fenye1?p={{ posts.next_page_number }}">下一页</a>
16 {% endif %}
17 <span>
18 {{ posts.number }}/{{ posts.paginator.num_pages }}
19 </span>
Paginator对象
全部数据:USER_LIST,=》得出共有多少条数据
per_page: 每页显示条目数量
count: 数据总个数
num_pages:总页数
page_range:总页数的索引范围,如: (1,10),(1,200)
page: page对象(是否具有下一页;是否有上一页;)
Page对象
# has_next 是否有下一页
# next_page_number 下一页页码
# has_previous 是否有上一页
# previous_page_number 上一页页码
# object_list 分页之后的数据列表,已经切片好的数据
# number 当前页
# paginator paginator对象