django 分页(2) 使用类 页码显示
django 分页显示页码
views.py
显示11页码 1 2 3 4 5 6 7 8 9 10 11 if 总页数(10) < 11 起始位置 1 - 10总页数 else 总页数 > 11 IF 当前页 小于 6 起始位置 1 结束页 11 IF 当前页 大于 6 IF 如果结束页 > 总页数 起始值 6 - 5 总页数 else 起始值 6 - 5 结束页 6+5
#!/usr/bin/env python #_*_coding:utf-8_*_ from django.shortcuts import render,render_to_response,redirect,HttpResponse from app01 import models from django.utils.safestring import mark_safe import common import html_helper # Create your views here. def index(request,page): page = common.try_int(page) hostcount = models.Host.objects.all().count() # 获取数据库的总共条数 pageobj = html_helper.PageInfo(page,hostcount) hostall = models.Host.objects.all()[pageobj.start:pageobj.end] # 一页显示的条数 page_html = html_helper.Pager(page,pageobj.all_page_count()) ret = {'data':hostall,'count':hostcount,'page_ret':page_html} return render_to_response('index.html',ret)
html_helper.py
#!/usr/bin/env python #_*_coding:utf-8_*_ from django.utils.safestring import mark_safe class PageInfo(object): def __init__(self,current_page,all_page_count,per_item=5): self.CurrentPage = current_page self.AllCount = all_page_count self.PerItem = per_item @property def start(self): return (self.CurrentPage - 1) * self.PerItem @property def end(self): return self.CurrentPage * self.PerItem def all_page_count(self): ''' tempcountpage = divmod(hostcount,pageint) if tempcountpage[1] == 0: all_page_count = tempcountpage[0] else: all_page_count = tempcountpage[0] +1 ''' tempcountpage = divmod(self.AllCount,self.PerItem) if tempcountpage[1] == 0: all_page_count = tempcountpage[0] else: all_page_count = tempcountpage[0] +1 return all_page_count def Pager(page,all_page_count): # 定义一个列表,然后循环总页数,追加到列表中, page_html = [] # 首页 first_page = '<a href="/index/%d">首页</a>' % (1) page_html.append(first_page) # 上一页 if page <= 1: up_page = '<a href="/index/%d">上一页</a>' % (1) else: up_page = '<a href="/index/%d">上一页</a>' % (page - 1) page_html.append(up_page) # 显示1。。。最后的页数 if all_page_count < 12: begin_page = 0 end_page = all_page_count else: if page < 6: begin_page = 0 end_page = 12 else: if page + 6 > all_page_count: begin_page = page - 6 end_page = all_page_count else: begin_page = page - 6 end_page = page + 6 for i in range(begin_page,end_page): if page == i + 1: temp_html = '<a class="selected" href="/index/%d">[%d]</a>' % (i + 1, i + 1) else: temp_html = '<a href="/index/%d">[%d]</a>' % (i + 1, i + 1) page_html.append(temp_html) # 下一页 if page >= all_page_count: next_page = '<a href="/index/%d">[下一页]</a>' % (all_page_count) else: next_page = '<a href="/index/%d">[下一页]</a>' % (page + 1) page_html.append(next_page) # 尾页 end_page = '<a href="/index/%d">[尾页]</a>' % (all_page_count) page_html.append(end_page) # 使用mark_safe 可让html显示返回的a标签。join 把列表取出用空格连接 page_html = mark_safe(' '.join(page_html)) return page_html