Django-分页
Django-分页
django内置的分页
Paginator对象
Page对象
示例
from django.core.paginator import Paginator def students(request, num): allStudents = Student.objects.all() #分页 每页6条数据 paginator = Paginator(allStudents, 6) print(paginator.count, paginator.num_pages, paginator.page_range) pageStus = paginator.page(num) return render(request, "students.html", {"stus":pageStus}) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>学生信息</title> </head> <body> <h1>学生信息</h1> <ul> {% for stu in stus %} <li>{{ stu.name }}--{{ stu.grade }}--{{ stu.age }}</li> {% endfor %} </ul> {% if stus.has_previous %} <a href="/students/{{ stus.previous_page_number }}">上一页</a> {% endif %} {% for index in stus.paginator.page_range %} {% if index == stus.number %} {{ index }} {% else %} <a href="/students/{{ index }}/">{{ index }}</a> {% endif %} {% endfor %} {% if stus.has_next %} <a href="/students/{{ stus.next_page_number }}">下一页</a> {% endif %} </body> </html>
django-pure-pagination 分页
(1)安装
pip install django-pure-pagination
(2)settings里面添加
INSTALLED_APPS = ( ... 'pure_pagination', )
(3)views中使用方法
class OrgView(View): '''课程机构''' def get(self, request): # 所有课程机构 all_orgs = CourseOrg.objects.all() # 有多少家机构 org_nums = all_orgs.count() # 所有城市 all_citys = CityDict.objects.all() # 对课程机构进行分页 # 尝试获取前台get请求传递过来的page参数 # 如果是不合法的配置参数默认返回第一页 try: page = request.GET.get('page', 1) except PageNotAnInteger: page = 1 # 这里指从allorg中取五个出来,每页显示5个 p = Paginator(all_orgs, 5, request=request) orgs = p.page(page) return render(request, "org-list.html", { "all_orgs": orgs, "all_citys": all_citys, "org_nums": org_nums, })
(4)模板修改
#{%for course_org in all_orgs%} {%for course_org in all_orgs.object_list%} ... {%endfor%}
(5)分页功能
<div class="pageturn"> <ul class="pagelist"> {% if all_orgs.has_previous %} <li class="long"><a href="?{{ all_orgs.previous_page_number.querystring }}">上一页</a></li> {% endif %} {% for page in all_orgs.pages %} {% if page %} {% ifequal page all_orgs.number %} <li class="active"><a href="?{{ page.querystring }}">{{ page }}</a></li> {% else %} <li><a href="?{{ page.querystring }}" class="page">{{ page }}</a></li> {% endifequal %} {% else %} <li class="none"><a href="">...</a></li> {% endif %} {% endfor %} {% if all_orgs.has_next %} <li class="long"><a href="?{{ all_orgs.next_page_number.querystring }}">下一页</a></li> {% endif %} </ul> </div>