分页功能代码:
1 from django.shortcuts import render 2 3 # Create your views here. 4 5 from app01 import models 6 7 8 9 def books(request):10 #从URL取参数11 page_num = request.GET.get("page")12 print(page_num,type(page_num))13 # 每一页显示多少条数据14 per_page = 1015 # 总数据是多少16 total_count = models.Book.objects.all().count()17 # 总共需要多少页码来展示18 total_page, m = divmod(total_count, per_page)19 if m:20 total_page += 121 try:22 page_num = int(page_num)23 # 如果输入的页码数超过了最大的页码数,默认返回最后一页的数据24 if page_num > total_page:25 page_num = total_page26 except Exception as e:27 #当输入的页码不是正经数字的时候,默认返回第一页的数据28 page_num = 129 30 31 #定义两个变量保存数据从哪儿取到哪儿32 data_start = (page_num-1)*1033 data_end = page_num*1034 35 36 37 #页面总共展示多少页码38 max_page = 1139 if total_page < max_page:40 max_page = total_page41 42 43 half_max_page = max_page // 244 #页面上展示的页码从哪儿开始45 page_start = page_num - half_max_page46 #页面上展示的页码到哪儿结束47 page_end = page_num + half_max_page48 #如果当前页减一半,比1还小49 if page_start <= 1:50 page_start = 151 page_end = max_page52 53 #如果当前页加一半比总页码数还大54 if page_end >= total_page:55 page_end = total_page56 page_start = total_page - max_page +157 58 all_book = models.Book.objects.all()[data_start:data_end]59 60 #自己拼接分页的HTML代码61 html_str_list = []62 #加上第一页63 html_str_list.append('