Python--day71--分页功能
分页功能代码:
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 = 10 15 # 总数据是多少 16 total_count = models.Book.objects.all().count() 17 # 总共需要多少页码来展示 18 total_page, m = divmod(total_count, per_page) 19 if m: 20 total_page += 1 21 try: 22 page_num = int(page_num) 23 # 如果输入的页码数超过了最大的页码数,默认返回最后一页的数据 24 if page_num > total_page: 25 page_num = total_page 26 except Exception as e: 27 #当输入的页码不是正经数字的时候,默认返回第一页的数据 28 page_num = 1 29 30 31 #定义两个变量保存数据从哪儿取到哪儿 32 data_start = (page_num-1)*10 33 data_end = page_num*10 34 35 36 37 #页面总共展示多少页码 38 max_page = 11 39 if total_page < max_page: 40 max_page = total_page 41 42 43 half_max_page = max_page // 2 44 #页面上展示的页码从哪儿开始 45 page_start = page_num - half_max_page 46 #页面上展示的页码到哪儿结束 47 page_end = page_num + half_max_page 48 #如果当前页减一半,比1还小 49 if page_start <= 1: 50 page_start = 1 51 page_end = max_page 52 53 #如果当前页加一半比总页码数还大 54 if page_end >= total_page: 55 page_end = total_page 56 page_start = total_page - max_page +1 57 58 all_book = models.Book.objects.all()[data_start:data_end] 59 60 #自己拼接分页的HTML代码 61 html_str_list = [] 62 #加上第一页 63 html_str_list.append('<li><a href="/books/?page=1">首页</a></li>') 64 #加上一个上一页的标签 65 #判断,如果是第一页就没有上一页了 66 if page_num <= 1: 67 html_str_list.append(' <li class="disabled"><a href="#" ><span aria-hidden="true">«</span></a><li>') 68 else: 69 #加上一个上一页的功能 70 html_str_list.append(' <li><a href="/books/?page={}" ><span aria-hidden="true">«</span></a><li>'.format(page_num-1)) 71 72 for i in range(page_start,page_end +1): 73 #如果是当前页就加一个active样式类 74 # if i == page_num: 75 # tmp = '<li class="active"><a href="/books/?page={0}">{0}</a></li>'.format(i) 76 # else: 77 if i == page_num: 78 tmp = '<li class="active"><a href="/books/?page={0}">{0}</a></li>'.format(i) 79 else: 80 tmp = '<li><a href="/books/?page={0}">{0}</a></li>'.format(i) 81 82 html_str_list.append(tmp) 83 84 #加上一个下一页的标签 85 #判断,如果是最后一页,就没有下一页 86 if page_num >= total_page: 87 html_str_list.append('<li class="disabled"><a href="#" aria-label="Next"><span aria-hidden="true">»</span></a><li>') 88 else: 89 html_str_list.append('<li><a href="/books/?page={}" aria-label="Next"><span aria-hidden="true">»</span></a><li>'.format(page_num+1)) 90 #加上最后一页 91 html_str_list.append('<li><a href="/books/?page={0}">末页</a></li>'.format(total_page)) 92 93 page_html = "".join(html_str_list) 94 95 96 97 return render(request,'books.html',{'books':all_book,"page_html":page_html})