django 操作分页代码实现
from django.utils.safestring import mark_safe #mark_safe可以使str标签变成HTML标签 class Paginstion(object): def __init__(self,current_page,data_count,per_page_count=6,page_num=7): try: self.current_page=int(current_page) #对当前页异常判断,不为负数和0 except Exception as e: self.current_page=1 self.data_count=data_count self.per_page_count=per_page_count self.page_num=page_num @property def start(self): return (self.current_page-1)*self.per_page_count #start和end为了每一页对应条数:11-20,31-40。。 @property def end(self): return self.current_page*self.per_page_count @property def total_count(self): #计算中共有多少个分页 x,y=divmod(self.data_count,self.per_page_count) if y: x+=1 return x def page_str(self,base_url): #方法最后返回分页标签 page_list=[] if self.total_count <self.page_num: start_index=1 #开始分页数字 end_index=self.total_count+1 #结束分页数字 else: if self.current_page<=(self.page_num+1)/2: #分页处于中间位置 start_index=1 end_index=self.page_num+1 else: start_index=self.current_page-(self.page_num-1)/2 #点击的分页数大于中间数 end_index=self.current_page+(self.page_num+1)/2 if (self.current_page+(self.page_num-1)/2) > self.total_count: #点击到最后一批分页了,怎么显示 start_index=self.total_count-self.page_num+1 end_index=self.total_count first='<li class="page"><a href="%s?p=%s">首页</a><li>'%(base_url,1) page_list.append(first) if self.current_page==1: prev='<li class="page"><a href="javascript:void(0);">上一页</a><li>' else: prev='<li class="page"><a href="%s?p=%s">上一页</a><li>' %(base_url,self.current_page-1) page_list.append(prev) for i in range(int(start_index),int(end_index)): if i == self.current_page: page_item='<li class="page active"><a href="%s?p=%s">%s</a><li>' %(base_url,i,i) else: page_item = '<li class="page"><a href="%s?p=%s">%s</a><li>' % (base_url, i, i) page_list.append(page_item) if self.current_page==self.total_count: next='<li class="page"><a href="javascript:void(0);">下一页</a><li>' else: next='<li class="page"><a href="%s?p=%s">下一页</a><li>' %(base_url,self.current_page+1) page_list.append(next) last = '<li class="page"><a href="%s?p=%s">尾页</a><li>' % (base_url, self.total_count) page_list.append(last) page_star=mark_safe(''.join(page_list)) return page_star