Django分页器

1.在页面显示分页数据,需要用到Django分页器组件

导入Paginator

from django.core.paginator import Paginator

 1 Paginator对象:    paginator = Paginator(user_list, 10)
 2 # per_page: 每页显示条目数量
 3 # count:    数据总个数
 4 # num_pages:总页数
 5 # page_range:总页数的索引范围,如: (1,10),(1,200)
 6 # page:     page对象    
 7 page对象:page=paginator.page(1)
 8 # has_next              是否有下一页
 9 # next_page_number      下一页页码
10 # has_previous          是否有上一页
11 # previous_page_number  上一页页码
12 # object_list           分页之后的数据列表
13 # number                当前页
14 # paginator             paginator对象

 

Django的分页器

view.py

 1 from django.shortcuts import render,HttpResponse
 2 
 3 # Create your views here.
 4 from app01.models import *
 5 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
 6 
 7 def index(request):
 8 
 9     '''
10     批量导入数据:
11 
12     Booklist=[]
13     for i in range(100):
14         Booklist.append(Book(title="book"+str(i),price=30+i*i))
15     Book.objects.bulk_create(Booklist)
16     '''
17 
18     '''
19 分页器的使用:
20 
21     book_list=Book.objects.all()
22 
23     paginator = Paginator(book_list, 10)
24 
25     print("count:",paginator.count)           #数据总数
26     print("num_pages",paginator.num_pages)    #总页数
27     print("page_range",paginator.page_range)  #页码的列表
28 
29 
30 
31     page1=paginator.page(1) #第1页的page对象
32     for i in page1:         #遍历第1页的所有数据对象
33         print(i)
34 
35     print(page1.object_list) #第1页的所有数据
36 
37 
38     page2=paginator.page(2)
39 
40     print(page2.has_next())            #是否有下一页
41     print(page2.next_page_number())    #下一页的页码
42     print(page2.has_previous())        #是否有上一页
43     print(page2.previous_page_number()) #上一页的页码
44 
45 
46 
47     # 抛错
48     #page=paginator.page(12)   # error:EmptyPage
49 
50     #page=paginator.page("z")   # error:PageNotAnInteger
51 
52     '''
53 
54 
55     book_list=Book.objects.all()
56 
57     paginator = Paginator(book_list, 10)
58     page = request.GET.get('page',1)
59     currentPage=int(page)
60 
61 
62     try:
63         print(page)
64         book_list = paginator.page(page)
65     except PageNotAnInteger:
66         book_list = paginator.page(1)
67     except EmptyPage:
68         book_list = paginator.page(paginator.num_pages)
69 
70 
71     return render(request,"index.html",{"book_list":book_list,"paginator":paginator,"currentPage":currentPage})

 

view.py 部分注释

 1 def chakanbook(request):
 2     '''
 3         批量导入
 4         Booklist = []
 5         for i in range(100):
 6 
 7              Booklist.append(models.Book(title="book" + str(i), price=20 + i * i))
 8 
 9         models.Book.objects.bulk_create(Booklist)
10 
11         :param request:
12         :return:
13         '''
14     book_list = models.Book.objects.all()# book_list打印的是一个对象  先查看所有的书
15     paginator=Paginator(book_list,5)  #这里的book_list必须是一个集合对象,把所有的书分页,一页有五个
16     print(paginator.page_range)  #range(1, 4)
17     num = request.GET.get("page",2)#得到页数范围,默认有1页
18     print(num,type(num))
19     book_list = paginator.page(num) #显示第一页的内容
20     return render(request,"chakan.html",{"book_list":book_list,"page_range":page_range,"num":int(num),"paginator":paginator})

 

index.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" 
 7     integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
 8 </head>
 9 <body>
10 
11 <div class="container">
12 
13     <h4>分页器</h4>
14     <ul>
15 
16         {% for book in book_list %}
17              <li>{{ book.title }} -----{{ book.price }}</li>
18         {% endfor %}
19 
20      </ul>
21 
22 
23     <ul class="pagination" id="pager">
24 
25                  {% if book_list.has_previous %}
26                     <li class="previous"><a href="/index/?page={{ book_list.previous_page_number }}">上一页</a></li>
27                  {% else %}
28                     <li class="previous disabled"><a href="#">上一页</a></li>
29                  {% endif %}
30 
31 
32                  {% for num in paginator.page_range %}
33 
34                      {% if num == currentPage %}
35                        <li class="item active"><a href="/index/?page={{ num }}">{{ num }}</a></li>
36                      {% else %}
37                        <li class="item"><a href="/index/?page={{ num }}">{{ num }}</a></li>
38 
39                      {% endif %}
40                  {% endfor %}
41 
42 
43 
44                  {% if book_list.has_next %}
45                     <li class="next"><a href="/index/?page={{ book_list.next_page_number }}">下一页</a></li>
46                  {% else %}
47                     <li class="next disabled"><a href="#">下一页</a></li>
48                  {% endif %}
49 
50             </ul>
51 </div>
52 
53 
54 
55 </body>
56 </html>

 

拓展

 1 def index(request):
 2 
 3 
 4     book_list=Book.objects.all()
 5 
 6     paginator = Paginator(book_list, 15)
 7     page = request.GET.get('page',1)
 8     currentPage=int(page)
 9 
10     #  如果页数十分多时,换另外一种显示方式
11     if paginator.num_pages>30:
12 
13         if currentPage-5<1:
14             pageRange=range(1,11)
15         elif currentPage+5>paginator.num_pages:
16             pageRange=range(currentPage-5,paginator.num_pages+1)
17 
18         else:
19             pageRange=range(currentPage-5,currentPage+5)
20 
21     else:
22         pageRange=paginator.page_range
23 
24 
25     try:
26         print(page)
27         book_list = paginator.page(page)
28     except PageNotAnInteger:
29         book_list = paginator.page(1)
30     except EmptyPage:
31         book_list = paginator.page(paginator.num_pages)
32 
33 
34     return render(request,"index.html",locals())

 

自定义分页组件的使用方法

  1 class Pagination(object):
  2     """
  3     自定义分页
  4     """
  5     def __init__(self,current_page,total_count,base_url,params,per_page_count=10,max_pager_count=11):
  6         try:
  7             current_page = int(current_page)
  8         except Exception as e:
  9             current_page = 1
 10         if current_page <=0:
 11             current_page = 1
 12         self.current_page = current_page
 13         # 数据总条数
 14         self.total_count = total_count
 15 
 16         # 每页显示10条数据
 17         self.per_page_count = per_page_count
 18 
 19         # 页面上应该显示的最大页码
 20         max_page_num, div = divmod(total_count, per_page_count)
 21         if div:
 22             max_page_num += 1
 23         self.max_page_num = max_page_num
 24 
 25         # 页面上默认显示11个页码(当前页在中间)
 26         self.max_pager_count = max_pager_count
 27         self.half_max_pager_count = int((max_pager_count - 1) / 2)
 28 
 29         # URL前缀
 30         self.base_url = base_url
 31 
 32         # request.GET
 33         import copy
 34         params = copy.deepcopy(params)
 35         params._mutable = True
 36         # 包含当前列表页面所有的搜索条件
 37         # {source:[2,], status:[2], gender:[2],consultant:[1],page:[1]}
 38         # self.params[page] = 8
 39         # self.params.urlencode()
 40         # source=2&status=2&gender=2&consultant=1&page=8
 41         # href="/hosts/?source=2&status=2&gender=2&consultant=1&page=8"
 42         # href="%s?%s" %(self.base_url,self.params.urlencode())
 43         self.params = params
 44 
 45     @property
 46     def start(self):
 47         return (self.current_page - 1) * self.per_page_count
 48 
 49     @property
 50     def end(self):
 51         return self.current_page * self.per_page_count
 52 
 53     def page_html(self):
 54         # 如果总页数 <= 11
 55         if self.max_page_num <= self.max_pager_count:
 56             pager_start = 1
 57             pager_end = self.max_page_num
 58         # 如果总页数 > 11
 59         else:
 60             # 如果当前页 <= 5
 61             if self.current_page <= self.half_max_pager_count:
 62                 pager_start = 1
 63                 pager_end = self.max_pager_count
 64             else:
 65                 # 当前页 + 5 > 总页码
 66                 if (self.current_page + self.half_max_pager_count) > self.max_page_num:
 67                     pager_end = self.max_page_num
 68                     pager_start = self.max_page_num - self.max_pager_count + 1   #倒这数11个
 69                 else:
 70                     pager_start = self.current_page - self.half_max_pager_count
 71                     pager_end = self.current_page + self.half_max_pager_count
 72 
 73         page_html_list = []
 74         # {source:[2,], status:[2], gender:[2],consultant:[1],page:[1]}
 75         # 首页
 76         self.params['page'] = 1
 77         first_page = '<li><a href="%s?%s">首页</a></li>' % (self.base_url,self.params.urlencode(),)
 78         page_html_list.append(first_page)
 79 
 80         # 上一页
 81         self.params["page"] = self.current_page - 1
 82         if self.params["page"] < 1:
 83             pervious_page = '<li class="disabled"><a href="%s?%s" aria-label="Previous">上一页</span></a></li>' % (
 84             self.base_url, self.params.urlencode())
 85         else:
 86             pervious_page = '<li><a href = "%s?%s" aria-label = "Previous" >上一页</span></a></li>' % (
 87             self.base_url, self.params.urlencode())
 88         page_html_list.append(pervious_page)
 89 
 90         # 中间页码
 91         for i in range(pager_start, pager_end + 1):
 92             self.params['page'] = i
 93             if i == self.current_page:
 94                 temp = '<li class="active"><a href="%s?%s">%s</a></li>' % (self.base_url,self.params.urlencode(), i,)
 95             else:
 96                 temp = '<li><a href="%s?%s">%s</a></li>' % (self.base_url,self.params.urlencode(), i,)
 97             page_html_list.append(temp)
 98 
 99         # 下一页
100         self.params["page"] = self.current_page + 1
101         if self.params["page"] > self.max_page_num:
102             self.params["page"] = self.current_page
103             next_page = '<li class="disabled"><a href = "%s?%s" aria-label = "Next">下一页</span></a></li >' % (
104             self.base_url, self.params.urlencode())
105         else:
106             next_page = '<li><a href = "%s?%s" aria-label = "Next">下一页</span></a></li>' % (
107             self.base_url, self.params.urlencode())
108         page_html_list.append(next_page)
109 
110         # 尾页
111         self.params['page'] = self.max_page_num
112         last_page = '<li><a href="%s?%s">尾页</a></li>' % (self.base_url, self.params.urlencode(),)
113         page_html_list.append(last_page)
114 
115         return ''.join(page_html_list)

 

1 """
2 自定义分页组件的使用方法:
3     pager_obj = Pagination(request.GET.get('page',1),len(HOST_LIST),request.path_info,request.GET)
4     host_list = HOST_LIST[pager_obj.start:pager_obj.end]
5     html = pager_obj.page_html()
6     return render(request,'hosts.html',{'host_list':host_list,"page_html":html})
7 """

 

批量查数据

1  #批量创建数据
2     # booklist = []
3     # for i in range(100):
4     #     booklist.append(models.Book(name="book" + str(i), price=20 + i * i))
5     #
6     # models.Book.objects.bulk_create(booklist)

 

posted @ 2018-09-16 15:04  Roc_Atlantis  阅读(190)  评论(0编辑  收藏  举报