定义一个分页类,封装起来,保存到目录下面方便调用:pagination.py
具体完整代码:
from django.utils.safestring import mark_safe #分页类 class Page(object): def __init__(self,current_page,data_count,per_page_count=10,page_num=11): """ current_page:当前页 data_count:数据量 per_page_count:每页显示多少行数据 page_num: 显示固定多少行页码 """ self.current_page = current_page 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 @property def end(self): """ 切片末尾值 """ return self.current_page * self.per_page_count @property def total_count(self): """ 总页码:v 余数:y total_count返回的就是总页码值 """ v,y=divmod(self.data_count,self.per_page_count) if y: v +=1 return v def page_str(self,base_url): """ 生成页码,上下页, 跳转等功能 base_url:接收用户的url """ self.base_url=base_url """ page_list:页码列表 """ 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.current_page -self.page_num +1 end_index = self.total_count +1 # 上一页 if self.current_page == 1: prev = '<a class="page" href="javascript:void(0)">上一页</a>' else: prev='<a class="page" href="/cmdb/%s/?p=%s">上一页</a>' %(self.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: temp = '<a class= " page active" href="/cmdb/%s/?p=%s">%s</a>' % (self.base_url, i, i) else: temp= '<a class= "page" href="/cmdb/%s/?p=%s">%s</a> ' % (self.base_url,i,i) page_list.append(temp) #下一页 if self.current_page == self.total_count: next = '<a class="page" href="javascript:void(0)">下一页</a>' else: next = '<a class="page" href="/cmdb/%s/?p=%s">下一页</a>' % (self.base_url, self.current_page + 1) page_list.append(next) #跳转指定页码 jump=""" <input type="text" name=choice /> <a onclick='jumpto(this,"/cmdb/%s/?p=");' id="ii1"><input type="button" value="Go"/></a> <script> function jumpto(ths,base){ var val=ths.previousSibling.value; if (val == "") { alert("内容不能为空"); }else if(val >%s){ alert("页码不存在"); }else{ location.href = base + val; } console.log(this) } </script> """ % (self.base_url) page_list.append(jump) #拼接字符串 page_str= "".join(page_list) page_str=mark_safe(page_str) return page_str
views视图:
—调用封装好的类
返回的page_str字符串到user_list.html界面进行渲染:
jquery代码:
tag:在页面通过include导入