Python中的分页管理
1,自定义分页
#utils文件夹下的page.py文件 class PagerHelper: #total_count总的页数,current_page当前页数,base_url页面用来分页显示的URL如http://127.0.0.1:8000/classes.html/?p=71 #base_url为/calsses.html per_page每一页有多少条数据 def __init__(self,total_count,current_page,base_url,per_page=10): self.total_count = total_count self.current_page = current_page self.base_url = base_url self.per_page = per_page @property def db_start(self): return (self.current_page -1) * self.per_page @property def db_end(self): return self.current_page * self.per_page #返回总的页数 def total_page(self): v, a = divmod(self.total_count, self.per_page) if a != 0: v += 1 return v #返回页码的HTML,默认是11页显示,小于11页时1-总页数, #当前页小于6页时总显示1-11页,当前页加5(最后一页大于总页数时)显示(总页数-11,总页数) def pager_str(self): v = self.total_page() pager_list = [] if self.current_page == 1: pager_list.append(‘<a href="javascript:void(0);">上一页</a>‘) else: pager_list.append(‘<a href="%s?p=%s">上一页</a>‘ % (self.base_url, self.current_page - 1,)) # 6,1:12 # 7,2:13 if v <= 11: pager_range_start = 1 pager_range_end = v else: if self.current_page < 6: pager_range_start = 1 pager_range_end = 11 + 1 else: pager_range_start = self.current_page - 5 pager_range_end = self.current_page + 5 + 1 if pager_range_end > v: pager_range_start = v - 10 pager_range_end = v + 1 for i in range(pager_range_start, pager_range_end): if i == self.current_page: pager_list.append(‘<a class="active" href="%s?p=%s">%s</a>‘ % (self.base_url, i, i,)) else: pager_list.append(‘<a href="%s?p=%s">%s</a>‘ % (self.base_url, i, i,)) if self.current_page == v: pager_list.append(‘<a href="javascript:void(0);">下一页</a>‘) else: pager_list.append(‘<a href="%s?p=%s">下一页</a>‘ % (self.base_url, self.current_page + 1,)) pager = "".join(pager_list) return pager
自定义分页
在函数中调用
#获取数据 total_count = 总的页数 current_page = 当前页数 ‘/classes.html‘ --> 当前分页的url 5 每一页显示数据,默认是10 ###### from utils.page import PagerHelper obj = PagerHelper(total_count, current_page, ‘/classes.html‘,5) pager = obj.pager_str() cls_list = models.Classes.objects.all()[obj.db_start:obj.db_end] # current_user = request.session.get(‘username‘) return render(request, ‘classes.html‘, {‘username‘: current_user, ‘cls_list‘: cls_list, ‘str_pager‘: pager})
在views中使用
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16