一、函数(自定)
1 def show_books(request): 2 url = request.path_info 3 all_book_list = models.Book.objects.all() 4 total_data = all_book_list 5 total_data_num = total_data.count() # 总数据条数 6 7 current_pagetag_id = request.GET.get('page') # 当前页码id 8 try: 9 current_pagetag_id = int(current_pagetag_id) 10 except Exception: 11 current_pagetag_id = 1 12 13 perpage_data_num = 10 # 每个页面展示数据条数 14 15 quotient, remainder = divmod(total_data_num, perpage_data_num) 16 total_pagetag_num = quotient if remainder == 0 else quotient+1 # 总页码数 17 18 # 控制当前页码乱入负数等等情况 19 if current_pagetag_id < 1: 20 current_pagetag_id = 1 21 elif current_pagetag_id > total_pagetag_num: 22 current_pagetag_id = total_pagetag_num 23 24 pagedata_start_id = (current_pagetag_id - 1) * 10 25 pagedata_end_id = current_pagetag_id * 10 26 27 display_pagetag_num = 9 # 页面中页码导航条显示的页码个数 28 left_pagetag_id = current_pagetag_id-display_pagetag_num//2 # 页码导航条最左边的页码id 29 right_pagetag_id = current_pagetag_id+display_pagetag_num//2 # 页码导航条最右边的页码id 30 31 # 两端控制溢出 32 if left_pagetag_id < 1: 33 left_pagetag_id = 1 34 right_pagetag_id = display_pagetag_num 35 if right_pagetag_id > total_pagetag_num: 36 right_pagetag_id = total_pagetag_num 37 left_pagetag_id = total_pagetag_num-display_pagetag_num+1 38 39 # 数据量不足的情况下,控制页码导航条的显示 40 if total_pagetag_num < display_pagetag_num: 41 left_pagetag_id = 1 42 right_pagetag_id = total_pagetag_num 43 44 pagetag_html = '' 45 first_page_html = '<li><a href="{}?page=1">首页</a></li>'.format(url) 46 last_page_html = '<li><a href="{}?page={}">尾页</a></li>'.format(url, total_pagetag_num) 47 prev_page_html = '<li><a href="{}?page={}">上一页</a></li>'.format(url, current_pagetag_id-1) 48 next_page_html = '<li><a href="{}?page={}">下一页</a></li>'.format(url, current_pagetag_id+1) 49 50 for i in range(left_pagetag_id, right_pagetag_id+1): 51 if i == current_pagetag_id: 52 pagetag_html += '<li class="active"><a href="{0}?page={1}">{1}</a></li>'.format(url, i) 53 else: 54 pagetag_html += '<li><a href="{0}?page={1}">{1}</a></li>'.format(url, i) 55 56 pagetag_html = prev_page_html+first_page_html+pagetag_html+last_page_html+next_page_html 57 58 all_book_list = total_data[pagedata_start_id:pagedata_end_id] 59 60 return render(request, 'book_list.html', {'all_book_list': all_book_list, 'pagetag_html': pagetag_html})