web-分页
pager模块:
class Pagination(object):
def __init__(self,current_pag,page_total,per_item_page=30,max_page_number=11):
# 当前页
try:
v = int(current_pag)
if v <= 0:
v = 1
self.current_pag = v
except Exception as e:
self.current_pag = 1
#全部数据
self.page_total = page_total
# 每页显示30条数据
self.per_item_page = per_item_page
#显示11个页码
self.max_page_number = max_page_number
@property
def start(self):
return (self.current_pag - 1) * self.per_item_page #切片开始位置使用当前页-1 * 每页要显示的数据数量
@property
def end(self):
return (self.current_pag) * self.per_item_page #切片结束位置使用当前页 * 每页要显示的数据数量
@property
def num_pages(self):
a,b = divmod(self.page_total,self.per_item_page) #所有数据显示的页码数量使用 divmod函数总数据数取余每页显示的数据数如果余数小数部分为0则返回a,否则返回a + 1
if b == 0:
return a
return a + 1
def page_number(self):
if self.num_pages < self.max_page_number: #如果总页数小于显示的最大页码数返回1-总页码数
return range(1,self.num_pages + 1)
median = self.max_page_number // 2 #最大页码数取中间部分
if self.current_pag <= median: #如果当前页小于等于中间页码返回1-11
return range(1,self.max_page_number + 1)
if self.current_pag > median: #如果当前页大于中间页码数返回当前页减中间页码,当前页加中间页码
if (self.current_pag + median) > self.num_pages: #如果当前页加中间页 大于 总页码数 返回 总页码数减最大页码数,总页码数
return range(self.num_pages - self.max_page_number,self.num_pages + 1)
return range(self.current_pag - median,self.current_pag + median + 1)
def page_number_str(self): #页面显示
page_list = [] #创建空列表
if self.current_pag == 1: #如果当前页等于1上一页隐藏,否则上一页等于当前页减1
prev_page = '<a href="#" style="display: none"></a>'
else:
prev_page = '<a href="/index.html?p=%s">上一页</a>' % (self.current_pag - 1)
page_list.append(prev_page)
for i in self.page_number():
temp = '<a href="/index.html?p=%s">%s</a>'% (i,i)
page_list.append(temp)
next_page = '<a href="/index.html?p=%s">下一页</a>' % (self.current_pag + 1)
page_list.append(next_page)
return ''.join(page_list)
views:
USER_LIST = []
for i in range(1,666):
root = 'root' + str(i) + 'age' + str(i)
USER_LIST.append(root)
def index(request):
from app01.pager import Pagination
current_pag = request.GET.get('p')
page_obj = Pagination(current_pag,666)
data = USER_LIST[page_obj.start:page_obj.end]
return render(request,'index.html',{'user_list':data,'page_obj':page_obj})
html:
<ul>
{% for item in user_list %}
<li>{{ item }}/{{ item }}</li>
{% endfor %}
</ul>
{% for i in page_obj.page_number %}
<a href="/index.html?p={{ i }}">{{ i }}</a>
{% endfor %}
<hr/>
{{ page_obj.page_number_str|safe }}