django中分页器
1.创建项目
2.在models中创建数据表
3.makemigrations和migrate进行数据迁移
4.使用pycharm自带的数据库拖动到左侧的database中形成表结构,注意:第一次使用必须下载驱动
5.在url中引用views创建路径
6.views中写视图函数
from django.shortcuts import render,HttpResponse,reverse,redirect # Create your views here. from app1.models import Book from django.core.paginator import Paginator,EmptyPage def index(request): ''' 批量插入数据: book_list = [] for i in range(100): book = Book(title='book_%s'%i,price=i*i) book_list.append(book) Book.objects.bulk_create(book_list) return render(request,'index.html') 分页器的使用: book_list=Book.objects.all() paginator = Paginator(book_list, 10) print("count:",paginator.count) #数据总数 print("num_pages",paginator.num_pages) #总页数 print("page_range",paginator.page_range) #页码的列表 page1=paginator.page(1) #第1页的page对象 for i in page1: #遍历第1页的所有数据对象 print(i) print(page1.object_list) #第1页的所有数据 page2=paginator.page(2) print(page2.has_next()) #是否有下一页 print(page2.next_page_number()) #下一页的页码 print(page2.has_previous()) #是否有上一页 print(page2.previous_page_number()) #上一页的页码 ''' book_list = Book.objects.all() paginator = Paginator(book_list,10) try: current_page_num = request.GET.get('page',1) current_page = paginator.page(current_page_num) except Exception as e: current_page_num=1 current_page = paginator.page(1) return render(request,'index.html',{'current_page':current_page,'paginator':paginator})
7.html代码
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </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="">上一页</a></li> {% endif %} {# 根据每页显示的进行分页#} {% for num in paginator.page_range %} {% if num == current_page_num %} <li class="active"><a href="?page={{ num }}">{{ num }}</a></li> {% else %} <li><a href="?page={{ num }}">{{ num }}</a></li> {% endif %} {% endfor %} {# 下一页的操作#} {% if current_page.has_next %} <li><a href="?page={{ current_page.next_page_number }}"aria-label="Previous"> <span aria-hidden="true">下一页</span></a></li></a></li> {%else %} <li class="disabled"><a href="">下一页</a></li> {% endif %} </ul> </nav> </body> </html>