Django自带分页
urls.py
1 from django.conf.urls import url 2 from django.contrib import admin 3 from app01 import views 4 5 6 urlpatterns = [ 7 8 # 查看django自带的上一页和下一页 9 url(r'^index.html$', views.index), 10 11 ]
views.py
1 from django.shortcuts import render,HttpResponse 2 from django.views import View 3 from app01 import models 4 from django.core.paginator import Paginator,Page,PageNotAnInteger,EmptyPage 5 # django自带的分页 6 def index(request): 7 """ 8 分页 9 :param request: 10 :return: 11 """ 12 # 往用户信息的数据表内插入300条用户信息 13 # for i in range(301): 14 # name="xuyuanyuan"+str(i) 15 # models.Userinfo.objects.create(username=name,age=20,ut_id=2) 16 17 choise_page=request.GET.get("page") 18 user_list=models.Userinfo.objects.all() 19 # paginator=Paginator(user_list,10)分页处理,每一页10条数据 20 paginator=Paginator(user_list,10) 21 # per_page: 每页显示条目数量 22 # count: 数据总个数 23 # num_pages:总页数 24 # page_range:总页数的索引范围,如: (1,10),(1,200) 25 # page: page对象 26 27 try: 28 result=paginator.page(choise_page) 29 # print(result)#QuerySet [<Userinfo: Userinfo object>, <Userinfo: Userinfo object>, 30 # 打印的result是一个个userinfo的对象 31 # print(result.object_list) 32 except PageNotAnInteger as e: 33 result=paginator.page(1) 34 except EmptyPage as e: 35 result=paginator.page(1) 36 37 # has_next 是否有下一页 38 # next_page_number 下一页页码 39 # has_previous 是否有上一页 40 # previous_page_number 上一页页码 41 # object_list 分页之后的数据列表 42 # number 当前页 43 # paginator paginator对象 44 45 return render(request,"index.html",{"result":result})
index.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <h1>用户列表</h1> 9 <ul> 10 {% for i in result.object_list %} 11 <li>姓名:{{ i.username }}</li> 12 {% endfor %} 13 </ul> 14 <div> 15 {% if result.has_previous %} 16 <a href="/index.html?page={{ result.previous_page_number }}">上一页</a> 17 {% endif %} 18 19 {% if result.has_next %} 20 <a href="/index.html?page={{ result.next_page_number }}">下一页</a> 21 {% endif %} 22 </div> 23 </body> 24 </html>