django中分页器的使用方法(初、高级版本)
效果图:方法如下:
1.简单版(较繁琐但是直观):
1.1 定义数据库模型(models.py)中添加表
class ProductSample(models.Model):
# 示例商品表
id = models.AutoField(db_column='ID', primary_key=True)# Field name made lowercase.
item_id = models.CharField(verbose_name="用户ID",max_length=255, blank=True, null=True)
title = models.TextField(verbose_name="标题",blank=True, null=True)
pict_url = models.CharField(verbose_name="商品图片链接",max_length=255, blank=True, null=True)
category = models.TextField(verbose_name="类别",blank=True, null=True)
brand_id = models.CharField(verbose_name="品牌ID",max_length=255, blank=True, null=True)
seller_id = models.CharField(verbose_name="卖家ID",max_length=255, blank=True, null=True)
def __str__(self):
return self.title
# class Meta:
# verbose_name = '商品信息'
# verbose_name_plural = verbose_name
class Meta:
managed = False
db_table = 'product_sample'1.2 路由(urls.py)中添加路径
path("home/", views.home,name='home'), #主页面1.3 在视图中(view.py)添加如下代码
from .models import ProductSample #导入表
from django.utils.safestring import mark_safe
"""
需要修改如下代码(替换为自己的表):
#数据总条数
total_count = 替换.objects.all().order_by('id').count()
#MySQL上获取数据
documents = 替换.objects.all().order_by('id')# 指定按 id 字段排序
"""
def home(request):
"""主页面"""
# 分页器设计
page = int(request.GET.get('page',1))
size = 10 #每页显示10条
start = (page - 1)*size
end = page*size
#数据总条数
total_count = ProductSample.objects.all().order_by('id').count()
#总页码
total_page_count, div = divmod(total_count, size)
if div:
total_page_count +=1
#MySQL上获取数据
documents = ProductSample.objects.all().order_by('id')# 指定按 id 字段排序
#计算初当前页的前五页和后五页
plus = 5
if total_page_count <= 2 * plus + 1:
#数据库中的数据较少,没有达到11页
start_page = 1
end_page = total_page_count
else:
#数据库中的数据较多 大于11页
#当前页<5时
if page <= plus:
start_page = 1
end_page = 2 * plus
else:
#当前页>5
#当前页+5总页码
if (page + plus ) > total_page_count:
start_page = total_page_count - 2 * plus
end_page = total_page_count
else:
start_page = page - plus
end_page = page + plus
#页码
page_str_list = []
#首页
page_str_list.append('<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}">首页</a></li>'.format(1))
#上一页
if page > 1:
prev = '<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}" aria-label="Previous">«</a></li>'.format(page-1)
else:
prev = '<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}" aria-label="Previous">«</a></li>'.format(1)
page_str_list.append(prev)
#页面
for i in range(start_page,end_page+1):
if i== page:
ele = '<li ><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}">{}</a></li>'.format(i,i)
else:
ele = '<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}">{}</a></li>'.format(i,i)
page_str_list.append(ele)
#下一页
if page < total_page_count:
next_page = '<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}" aria-label="Next">»</a></li>'.format(page+1)
else:
next_page = '<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}" aria-label="Next">»</a></li>'.format(total_page_count)
page_str_list.append(next_page)
#尾页
page_str_list.append('<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}">尾页</a></li>'.format(total_page_count))
#搜索
search_string ="""
<li>
<formmethod="get">
<input name="page"
type="text"placeholder="页码">
<button type="submit">跳转</button>
</form>
</li>
"""
page_str_list.append(search_string)
page_string = mark_safe("".join(page_str_list))
return render(request,'home/home.html',locals())1.4 html页面使用分页器
{% for d in documents %}
{{ d.pict_url }}
{{ d.title }}
<p>价格:${{ random_num }}</p>
{% endfor %}
<nav aria-label="Page navigation">
<ul >
{{ page_string }}
</ul>
</nav>
{% endblock %}2 高级版(设置组件,可用于其他数据的分页)
2.1 自定义分页组件(在app里面新建一个utils目录,在utils里面新建一个pagination.py文件)将下面代码添加到pagination.py文件中,使用说明如下:
缺点:搜索+分页器时,不能将搜索的情况保留(下面有改进版,按需设计)
"""
自定义的分页组件,以后想要使用这个分页组件,需要做如下几件事:
#在视图函数中:
from home.utils.pagination import Pagination
def home(request):
# 1.根据自己的情况去筛选自己的数据
queryset = ProductSample.objects.all()
# 2.实例化分页对象
page_object = Pagination(request,queryset)
page_queryset = page_object.page_queryset#分页后的数据
page_string = page_object.html()#页码
return render(request,'home/home.html',locals())
#在HTML页面中:
{% for d in page_queryset %}
<h4> {{ d.title }} </h4>
{% endfor %}
<ul >
{{ page_string }}
</ul>
"""
from django.utils.safestring import mark_safe
class Pagination(object):
def __init__(self,request,queryset,size = 10, plus=5, page_param="page"):
"""
:param request: 请求的对象
:param queryset: 符合条件的数据(对该数据进行分页处理)
:param size:每页显示多少条数据
:param plus:显示当前页的前或后几页(页码)
:param page_param:在URL中传递的获取分页的参数,例如:/home/?page=12
"""
page = request.GET.get(page_param, "1")
if page.isdecimal():
page = int(page)
else:
page = 1
self.page = page
self.size = size# 每页显示10条
self.start = (page - 1) * size
self.end = page * size
self.page_queryset =queryset
# 数据总条数
total_count = queryset.count()
# 总页码
total_page_count, div = divmod(total_count, size)
if div:
total_page_count += 1
self.total_page_count = total_page_count
self.plus = plus
def html(self):
# 计算初当前页的前五页和后五页
if self.total_page_count <= 2 * self.plus + 1:
# 数据库中的数据较少,没有达到11页
start_page = 1
end_page = self.total_page_count
else:
# 数据库中的数据较多 大于11页
# 当前页<5时
if self.page <= self.plus:
start_page = 1
end_page = 2 * self.plus
else:
# 当前页>5
# 当前页+5总页码
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
# 页码
page_str_list = []
# 首页
page_str_list.append('<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}">首页</a></li>'.format(1))
# 上一页
if self.page > 1:
prev = '<li><a target="_blank" href ="/home/?page={}" aria-label="Previous">«</a></li>'.format(
self.page - 1)
else:
prev = '<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}" aria-label="Previous">«</a></li>'.format(
1)
page_str_list.append(prev)
# 页面
for i in range(start_page, end_page + 1):
if i == self.page:
ele = '<li ><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}">{}</a></li>'.format(i, i)
else:
ele = '<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}">{}</a></li>'.format(i, i)
page_str_list.append(ele)
# 下一页
if self.page < self.total_page_count:
next_page = '<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}" aria-label="Next">»</a></li>'.format(
self.page + 1)
else:
next_page = '<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}" aria-label="Next">»</a></li>'.format(
self.total_page_count)
page_str_list.append(next_page)
# 尾页
page_str_list.append('<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?page={}">尾页</a></li>'.format(self.total_page_count))
# 搜索
search_string = """
<li>
<formmethod="get">
<input name="page"
type="text"placeholder="页码">
<button type="submit">跳转</button>
</form>
</li>
"""
page_str_list.append(search_string)
page_string = mark_safe("".join(page_str_list))
return page_string3 高级版的升级(搜索+分页)
修改pagination.py文件。原理:保留参数
问题:跳转不能实现搜索的跳转,处理办法,结合Ajax来实现。
"""
自定义的分页组件,以后想要使用这个分页组件,需要做如下几件事:
在视图函数中:
from home.utils.pagination import Pagination
def home(request):
# 1.根据自己的情况去筛选自己的数据
queryset = ProductSample.objects.all()
# 2.实例化分页对象
page_object = Pagination(request,queryset)
page_queryset = page_object.page_queryset#分页后的数据
page_string = page_object.html()#页码
return render(request,'home/home.html',locals())
#在HTML页面中:
{% for d in page_queryset %}
<h4> {{ d.title }} </h4>
{% endfor %}
<ul >
{{ page_string }}
</ul>
"""
from django.utils.safestring import mark_safe
class Pagination(object):
def __init__(self,request,queryset,size = 10, plus=5, page_param="page"):
"""
:param request: 请求的对象
:param queryset: 符合条件的数据(对该数据进行分页处理)
:param size:每页显示多少条数据
:param plus:显示当前页的前或后几页(页码)
:param page_param:在URL中传递的获取分页的参数,例如:/home/?page=12
"""
fromdjango.http.request import QueryDict
import copy
query_dict = copy.deepcopy(request.GET)
query_dict._mutable = True
self.query_dict = query_dict
self.page_param = page_param
page = request.GET.get(page_param, "1")
if page.isdecimal():
page = int(page)
else:
page = 1
self.page = page
self.size = size# 每页显示10条
self.start = (page - 1) * size
self.end = page * size
self.page_queryset =queryset
# 数据总条数
total_count = queryset.count()
# 总页码
total_page_count, div = divmod(total_count, size)
if div:
total_page_count += 1
self.total_page_count = total_page_count
self.plus = plus
def html(self):
# 计算初当前页的前五页和后五页
if self.total_page_count <= 2 * self.plus + 1:
# 数据库中的数据较少,没有达到11页
start_page = 1
end_page = self.total_page_count
else:
# 数据库中的数据较多 大于11页
# 当前页<5时
if self.page <= self.plus:
start_page = 1
end_page = 2 * self.plus
else:
# 当前页>5
# 当前页+5总页码
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
# 页码
page_str_list = []
self.query_dict.setlist(self.page_param,)
# 首页
page_str_list.append('<li><a target="_blank" target="_blank" target="_blank" target="_blank" href ="?{}">首页</a></li>'.format(self.query_dict.urlencode()))
# 上一页
if self.page > 1:
self.query_dict.setlist(self.page_param, )
prev = '<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?{}" aria-label="Previous">«</a></li>'.format(
self.query_dict.urlencode())
else:
self.query_dict.setlist(self.page_param, )
prev = '<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?{}" aria-label="Previous">«</a></li>'.format(
self.query_dict.urlencode())
page_str_list.append(prev)
# 页面
for i in range(start_page, end_page + 1):
if i == self.page:
self.query_dict.setlist(self.page_param, )
ele = '<li ><a target="_blank" target="_blank" target="_blank" target="_blank" href ="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
else:
self.query_dict.setlist(self.page_param, )
ele = '<li><a target="_blank" target="_blank" target="_blank" target="_blank" href ="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
page_str_list.append(ele)
# 下一页
if self.page < self.total_page_count:
self.query_dict.setlist(self.page_param, )
next_page = '<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?{}" aria-label="Next">»</a></li>'.format(
self.query_dict.urlencode())
else:
self.query_dict.setlist(self.page_param, )
next_page = '<li><a target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" target="_blank" href ="?{}" aria-label="Next">»</a></li>'.format(
self.query_dict.urlencode())
page_str_list.append(next_page)
# 尾页
self.query_dict.setlist(self.page_param, )
page_str_list.append('<li><a target="_blank" target="_blank" target="_blank" target="_blank" href ="?{}">尾页</a></li>'.format(self.query_dict.urlencode()))
# 搜索
search_string = """
<li>
<formmethod="get">
<input name="page"
type="text"placeholder="页码">
<button type="submit">跳转</button>
</form>
</li>
"""
page_str_list.append(search_string)
page_string = mark_safe("".join(page_str_list))
return page_string
来源:https://www.cnblogs.com/Pluto-Love-Learn/p/18088226
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页:
[1]