Django_Paginator分页器
分页器代码说明
import os import random # 需要导入分页器类 from django.core.paginator import Paginator, EmptyPage # 导入配置django配置文件 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dailyfresh.settings') iterable_obj = [random.randint(1, 100) for i in range(45)] # 必须为可迭代对象,比如 QuerySet, list, tuple print(iterable_obj) # 实例化分页器 paginator = Paginator(object_list=iterable_obj, per_page=20) # 每页显示数据量 print("每页显示数据量:%s" % paginator.per_page) # 总页数 print("总页数:%s" % paginator.num_pages) # 数据总数 print("数据总数:%s" % paginator.count) # 获取某页的page对象,如果为不存在的页码会抛EmptyPage异常 try: page_obj = paginator.page(random.randint(1, 4)) except EmptyPage: page_obj = paginator.page(1) print("[异常]获取page对象超出范围") print(page_obj) print("通过page对象获取分页器实例", page_obj.paginator) # 获取当前页码 print("获取当前页码:%s" % page_obj.number) # 获取当前页内容 print("获取当前页内容:%s" % page_obj.object_list) # 校验是否有上一页,返回布尔值 print("是否有上一页:%s" % page_obj.has_previous()) # 上一页页码。如果无上一页,则抛错 print("上一页页码:%s" % page_obj.previous_page_number()) # 校验是否有下一页,返回布尔值 print("是否有下一页:%s" % page_obj.has_next()) # 下一页页码。如果无下一页,则抛错 print("下一页页码:%s" % page_obj.next_page_number())
执行结果如下:
简单demo
定义视图
from django.views import View class DemoView(View): def get(self, request, page_num): iterable_obj = [i for i in range(45)] # 对数据进行分页 paginator = Paginator(iterable_obj, 10) cur_page = paginator.page(page_num) content = { "cur_page": cur_page, } return render(request, "demo.html", content)
添加路由
from django.urls import re_path, path from apps.goods import views # 定义命名空间 app_name = "goods" urlpatterns = [ re_path("demo_list/(?P<page_num>\d+)", views.DemoView.as_view(), name="demo_list") ]
添加demo.html模板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!-- 展示每页信息 --> <ul> {% for v in cur_page.object_list %} <li>{{v}}</li> {% endfor %} </ul> <!-- 生成页码信息 --> <div> {% if cur_page.has_previous %} <a href="{% url 'goods:demo_list' cur_page.previous_page_number %}">上一页</a> {% endif %} {% for page_num in cur_page.paginator.page_range %} <a href="{% url 'goods:demo_list' page_num %}">{{ page_num }}</a> {% endfor %} {% if cur_page.has_next %} <a href="{% url 'goods:demo_list' cur_page.next_page_number %}">下一页</a> {% endif %} </div> </body> </html>
界面第5页展示如下: