1 from django.shortcuts import render, HttpResponse
2
3 # Create your views here.
4 from django.core.paginator import Paginator, EmptyPage
5 from app01 import models
6
7
8 # def index(request):
9 # # 你们 写:
10 # # for i in range(100):
11 # # models.Book.objects.create(name='图书%s'%i,price=10+i)
12 # # 我写和以后你们写(批量插入)
13 # # 先造成100本书,放到列表中
14 # # ll=[]
15 # # for i in range(100):
16 # # ll.append(models.Book(name='图书%s'%i,price=10+i))
17 # # # 批量插入,两个参数,第一个是对象列表,第二个是一次插入的数据量,不填,默认一次全插入
18 # # models.Book.objects.bulk_create(ll)
19 #
20 # # 查询所有图书
21 # book_list=models.Book.objects.all()
22 # # 分页器--类
23 # # 实例化产生一个对象
24 # # 两个参数:object_list:对象列表, per_page:每页显示的条数
25 # paginator=Paginator(book_list,10)
26 # # 对象内的属性
27 # # 数据总条数100条
28 # # print(paginator.count)
29 # # # 总页数 10页
30 # # print(paginator.num_pages)
31 # # # 页码数的列表
32 # # print(paginator.page_range)
33 # # # 取到第 x 页 ,返回一个Page对象
34 # # current_page=paginator.page(5)
35 # # # 当前页码内所有的数据
36 # # print(current_page.object_list)
37 # # # 是否有下一页
38 # # print(current_page.has_next())
39 # # # 是否有上一页
40 # # print(current_page.has_previous())
41 # # # 下一页页码数
42 # # print(current_page.next_page_number())
43 # # # 上一页的页码数
44 # # print(current_page.previous_page_number())
45 #
46 #
47 # return render(request,'index.html',locals())
48
49 # def index(request):
50 # book_list = models.Book.objects.all()
51 #
52 # paginator = Paginator(book_list, 3)
53 # # 当前页码
54 # try:
55 # current_page_num = int(request.GET.get('page'))
56 # current_page = paginator.page(current_page_num)
57 # # 当前页码所有数据
58 # print(current_page.object_list)
59 # # 即可以循环current_page.object_list,又可以循环当前页的对象
60 # # for item in current_page:
61 # # print(item.name)
62 # # except EmptyPage as e:
63 # # # 捕获异常后,跳到第一页
64 # # current_page_num = 1
65 # # current_page = paginator.page(current_page_num)
66 # except Exception as e:
67 # current_page_num = 1
68 # current_page = paginator.page(current_page_num)
69 #
70 # return render(request, 'index.html', locals())
71
72 def index(request):
73 book_list = models.Book.objects.all()
74 paginator = Paginator(book_list, 3)
75 # 如果页码数多,让它显示前5,后5,中间是当前在的页码
76 try:
77
78 current_page_num = int(request.GET.get('page'))
79 current_page = paginator.page(current_page_num)
80 print(current_page.object_list)
81 # 总页码数,大于11的时候
82 if paginator.num_pages >11:
83 # 当前页码数-5大于1的时候,page_range应该是?
84 if current_page_num-5<1:
85 page_range=range(1,12)
86 elif current_page_num+5>paginator.num_pages:
87 # 当前页码数+5大于总页码数,总页码数往前推11个
88 page_range=range(paginator.num_pages-10,paginator.num_pages+1)
89 else:
90 page_range = range(current_page_num - 5, current_page_num + 6)
91 else:
92 #小于11,有多少页,就显示多少页
93 page_range=paginator.page_range
94 except Exception as e:
95 current_page_num = 1
96 current_page = paginator.page(current_page_num)
97
98 return render(request, 'index_next.html', locals())