效果展示,根据当前页码显示前后各5页,有首页和尾页,上一页和下一页
pytho代码
新建py文件:pageination.py
"""自定义分页组件"""
from django.utils.safestring import mark_safe
class Pageination(object):
"""
:param request: 请求的对象
:param queryset: 符合条件的数据(根据这个数据给他进行分页处理)
:param page_size: 每页显示多少条数据
:param page_param: 在URL中传递的获取分页的参数,例如:/etty/list/?page=12
:param plus: 显示当前页的 前或后几页(页码)
"""
def __init__(self, request, queryset, page_size=10, page_param='page', plus=5):
page = request.GET.get('page', 1)
# 判断是否为字符串十足
if page.isdecimal():
page = int(page)
else:
page = 1
# 获取当前页
self.page = page
# 每页显示条数
self.page_size = page_size
# 起始页
self.start = (page - 1) * page_size
# 结束页
self.end = page * page_size
self.page_queryset = queryset[self.start:self.end]
# 总条数
total_count = queryset.count()
total_page_count, div = divmod(total_count, page_size) # 获取整除数 与 余数
if div:
total_page_count += 1
# 总页码
self.total_page_count = total_page_count
# 显示页码数
self.plus = plus
def html(self):
# 计算出当前页前5页,和后5页
if self.total_page_count <= 2 * self.plus + 1:
start_page = 1
end_page = self.total_page_count
else:
# 数据空中的数据表较多 >11
if self.page <= self.plus:
start_page = 1
end_page = 2 * self.plus + 1
else:
if (self.page + self.plus) > self.total_page_count:
start_page = self.total_page_count - 2 * self.plus
end_page = self.total_page_count
else:
start_page = self.page - self.plus
end_page = self.page + self.plus + 1
# 生成页码
page_str_list = []
# 首页
page_str_list.append('首页 ')
# 上一页
if self.page > 1:
prev = f'上一页 '
else:
prev = f'上一页 '
page_str_list.append(prev)
for i in range(start_page, end_page + 1):
if i == self.page:
ele = f'{i} '
else:
ele = f'{i} '
page_str_list.append(ele)
# 下一页
if self.page < self.total_page_count:
prev = f'下一页 '
else:
prev = f'下一页 '
page_str_list.append(prev)
# 尾页
page_str_list.append(f'尾页 ')
# 输入页码跳转
search_string = """
"""
page_str_list.append(search_string)
# 转换为HTML元素
page_string = mark_safe(''.join(page_str_list))
return page_string
调用页码:
page_object = Pageination(request, queryset)
context = {
'queryset': page_object.page_queryset,
'search_data': search_data, # 分完页的数据
'page_string': page_object.html(), # 页码
}
return render(request, 'pretty_list.html', context)
html中使用