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>
地址html
(1)安裝python
pip install django-pure-pagination
(2)settings裏面添加git
INSTALLED_APPS = ( ... 'pure_pagination', )
(3)views中使用方法github
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)模板修改django
#{%for course_org in all_orgs%} {%for course_org in all_orgs.object_list%} ... {%endfor%}
(5)分頁功能segmentfault
<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>