class PageInfo(object): def __init__(self,current_page,all_count,per_page,show_page=11): try: #如果用户传入的页码异常 就让页码=1 self.current_page=int(current_page) except Exception: self.current_page = 1 self.show_page=show_page self.per_page=per_page a,b=divmod(all_count,per_page) #计算显示数据库一共需要 多少总页码 if b: a=a+1 self.all_page=a def start(self): return (self.current_page-1)* self.per_page def stop(self): return self.current_page*self.per_page def pager(self): #该方法专门用于 在前端显示页码 half=int((self.show_page-1)/2) #如数据库 数据条目 小于 11条 if self.all_page < self.show_page: begin=1 stop=self.all_page+1 else: #如果当前页小于=5 起始页再减去5就是负数了那么 就 显示0-11页码 if self.current_page<=half: begin =1 stop=self.show_page+1 else: begin=self.current_page-half stop=self.current_page+half+1 page_list = [] if self.current_page<=1: #如果当前页是1了就不要在上一页了 b = ‘<a href="/custom.html?page=#">上一页</a>‘ else: b=‘<a href="/custom.html?page=%s">上一页</a>‘%(self.current_page-1) page_list.append(b) for i in range(begin,stop): if i ==self.current_page: temp=‘<a style="display: inline-block;padding: 5px;margin: 5px;background-color: bisque" href="/custom.html?page=%s">%s</a>‘%(i,i) else: temp = ‘<a style="display: inline-block;padding: 5px;margin: 5px;background-color:blueviolet" href="/custom.html?page=%s">%s</a>‘% (i,i) page_list.append(temp) return ‘‘.join(page_list) def custom(request): all_count=models.UserInfo.objects.all().count()#计算一共 数据库中一共多少条数据 user_info=PageInfo(request.GET.get(‘page‘),all_count,10) user_list=models.UserInfo.objects.all()[user_info.start():user_info.stop()] return render(request,‘custom.html‘,{‘user_list‘:user_list,‘page_info‘:user_info})
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> {% for row in user_list %} <li>{{ row.name }}</li> {% endfor %} </ul> {{ page_info.pager|safe}} {# 把Python的对象传入模板,自动执行,|safe 显示#} </body> </html>
原文:http://www.cnblogs.com/sss4/p/7082713.html