在Django 项目中使用自带的分页模块,记录如下
相关说明
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| from django.core.paginator import Paginator objects = ['abc','bcd','cde','def','efg','fgh'] p = Paginator(objects, 2) p.cout p.num_pages p.per_page p.object_list p.page_range p1 = p.page(1) p1.object_list p1.has_next() p1.has_previous() p1.has_other_pages() p1.start_index() p1.end_index() p1.next_page_number() p1.previous_page_number() p1.paginator
|
Django中使用分页
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| from django.shortcuts import render_to_response from django.core.paginator import Paginator, EmptyPage, InvalidPage, PageNotAnInteger from models import * def device_status(request): All_page_info = Device_status.objects.all() DataCount,page,All_page_info = All_in_one(request,All_page_info) return my_render("serverinfo/device_status.html",locals(),request) def my_render(template,data,request): return render_to_response(template, data, context_instance=RequestContext(request)) def getpage_id(request): """ 传递前端page过来的值,如果没有设置为1 """ page = request.GET.get("page","") if page: page = request.GET.get("page","") else: page = 1 return page def getpages(Data,page): """ 处理分页函数 """ paginator = Paginator(list(Data),2) try: Data = paginator.page(page) except PageNotAnInteger: Data = paginator.page(1) except EmptyPage: Data = paginator.page(paginator.num_pages) return Data,page def All_in_one(request,All_page_info): DataCount = len(All_page_info) page = getpage_id(request) All_page_info,page=getpages(All_page_info,page) return DataCount,page,All_page_info
|
templates中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 备注:paginator.html //将以下模板导入需要添加分页功能的页面即可({% include 'paginator.html' %}) ========================= <span class="step-links"> {% if All_page_info.has_previous %} <!-- 是否有前一页 --> <a href="?page={{ All_page_info.previous_page_number }}">上一页</a> <!-- 前一页的页码 --> </script> {% endif %} <span class="current"> 第 {{ All_page_info.number }}页 总 {{ All_page_info.paginator.num_pages }} 页 <!-- 总页数 --> </span> {% if All_page_info.has_next %} <a href="?page={{ All_page_info.next_page_number }}">下一页</a> <!-- 后一页的页码 --> {% endif %} </span> <span> 共{{DataCount}}条记录 </span>
|
效果展示