Django自帶分頁
阿新 • • 發佈:2017-07-03
per ews eat tor pla ont models obj pre
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 importView CodeView 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>View Code
Django自帶分頁