class Pages: def __init__(self, current_page, data_count, per_page_count=10, pager_num=7):#pager_num 这是页码 self.current_page = current_page self.data_count = data_count self.per_page_count = per_page_count self.pager_num = pager_num pass @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 all_count(self): v, s = divmod(self.data_count, self.per_page_count) if s > 0: v += 1 return v def page_str(self, base_url): pg = [] if self.all_count < self.pager_num: start_index = 1 ent_index = self.all_count else: if self.current_page < (self.pager_num + 1) / 2: # 最前面的数,当小于6时会出现的一种情况 start_index = 1 ent_index = self.pager_num elif self.current_page + 5 > self.all_count: # 最后面的数,当加上5大于总页数时会出现的一种情况 start_index = self.all_count - self.pager_num + 1 ent_index = self.all_count else: start_index = self.current_page - ((self.pager_num - 1) / 2) ent_index = self.current_page + ((self.pager_num - 1) / 2) pre_page = "<a href='%s?p=%s' class='page'>上一页</a>" % (base_url, self.current_page - 1 if self.current_page > 1 else 1) for a in range(int(start_index), int(ent_index)+1): if a == self.current_page: temp = "<a href='%s?p=%s' class='page active'>%s</a>" % (base_url, a, a) pg.append(temp) else: temp = "<a href='%s?p=%s' class='page'>%s</a>" % (base_url, a, a) pg.append(temp) next_page = "<a href='%s?p=%s' class='page'>下一页</a>" % (base_url, self.current_page + 1 if self.current_page < self.all_count else self.all_count) jump = """ <input id="jump" type="text"><button onclick="jump(this)">跳转</button> <script> function jump(node){ location.href= '%s?p='+ $("#jump").val() } </script> """ % base_url page_str = pre_page+"".join(pg)+next_page+jump return page_str
使用例子:
def show_vedio(request): current_page = request.GET.get("p", 1) current_page = int(current_page) page_obj = Pages(current_page, len(LIST)) lists = LIST[page_obj.start:page_obj.end] return render(request, "blogs/internet/show_video.html", {"list": lists, "page": page_obj.page_str("/blogs/video/")})
前端:
{{ "分页 "|defined_filter:"您会做 了吗!" }} <ul> {% for i in list %} <li>{{ i }}</li> {% endfor %} </ul> {{ page|safe }}