views.py
def index(request): # 效率低,每次都要insert一下 # for i in range(100): # Book.objects.create( # title=f‘book_{i}‘, # price=i * i‘ # ) # 批量导入,一条insert后面对应100条数据 # book_list = [] # for i in range(100): # book = Book(title=f‘book_{i}‘, price=i * i) # book_list.append(book) # # Book.objects.bulk_create(book_list) book_list = Book.objects.all() # 分页器 paginator = Paginator(book_list, 3) print("count:", paginator.count) # 数据总数 print("num_pages", paginator.num_pages) # 总页数 print("page_range", paginator.page_range) # 页码的列表 # 抛错 # page=paginator.page(12) # error:EmptyPage # page=paginator.page("z") # error:PageNotAnInteger current_page_num = int(request.GET.get(‘pa ge‘, 1)) if paginator.num_pages > 11: if current_page_num - 5 < 1: page_range = range(1, 11) elif current_page_num + 5 > paginator.num_pages: page_range = range(paginator.num_pages - 10, paginator.num_pages + 1) # range顾头不顾尾 else: page_range = range(current_page_num - 5, current_page_num + 6) else: page_range = paginator.page_range try: current_page = paginator.page(current_page_num) # 显示某一页具体数据的两种方式 print(‘object_list‘, current_page.object_list) for i in current_page: print(i) except EmptyPage as e: current_page = paginator.page(1) # print(current_page.has_next()) # 是否有下一页 # print(current_page.next_page_number()) # 下一页的页码 # print(current_page.has_previous()) # 是否有上一页 # print(current_page.previous_page_number()) # 上一页的页码 return render(request, ‘index.html‘, locals())
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <link rel="stylesheet" href="/static/bs/css/bootstrap.css"> </head> <body> <ul> {% for book in current_page %} <li>{{ book.title }} : {{ book.price }}</li> {% endfor %} </ul> <nav aria-label="Page navigation"> <ul class="pagination"> {% if current_page.has_previous %} <li> <a href="?page={{ current_page.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">上一页</span> </a> </li> {% else %} <li class="disabled"> <a href="" aria-label="Previous"> <span aria-hidden="true">上一页</span> </a> </li> {% endif %} {% for item in page_range %} {% if current_page_num == item %} <li class="active"><a href="?page={{ item }}">{{ item }}</a></li> {% else %} <li><a href="?page={{ item }}">{{ item }}</a></li> {% endif %} {% endfor %} {% if current_page.has_next %} <li> <a href="?page={{ current_page.next_page_number }}" aria-label="Next"> <span aria-hidden="true">下一页</span> </a> </li> {% else %} <li class="disabled"> <a href="" aria-label="Next"> <span aria-hidden="true">下一页</span> </a> </li> {% endif %} </ul> </nav> </body> </html>
原文地址:https://www.cnblogs.com/lshedward/p/10351884.html
时间: 2024-11-06 09:50:15