导入分页模块
from django.core.paginator import Paginator
实例化对象
paginator = Paginator(list, 10) # 将list分为每页10条数据
Paginator类对象的属性
序号 | 属性名 | 说明 |
---|---|---|
1 | num_pages | 返回分页之后的总页数 |
2 | page_range | 返回分页后的页码列表 |
Paginator类对象的方法
序号 | 方法名 | 说明 |
---|---|---|
1 | page(self, number) | 返回第number页的page类实例对象 |
Page实例对象的属性
序号 | 属性名 | 说明 |
---|---|---|
1 | number | 返回当前页的页码 |
2 | object_list | 返回当前页的数据查询集 |
3 | paginator | 返回对应的Paginator类对象 |
Page实例对象的方法
序号 | 方法名 | 说明 |
---|---|---|
1 | has_previous | 判断当前页是否有前一页 |
2 | has_next | 判断当前页是否有下一页 |
3 | previous_page_number | 返回前一页的页码 |
4 | next_page_number | 返回下一页的页码 |
视图:
from django.core.paginator import * # 导入分页模块 def pag(request, qqq): if qqq == '': # 当路径传值为空时,打开第一页 qqq = 1 pag_list = ['qqq', 'www', 'eee', 'aaa', 'qqq', 'www', 'eee', 'aaa''qqq', 'www', 'eee', 'aaa'] paginator = Paginator(pag_list, 3) # 每页3个 page = paginator.page(int(qqq)) # 获取第几页的内容 return render(request, 'pag.html', {'page': page})
模板:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>分页</title> </head> <body> <ul> {#循环输出页面内容#} {% for i in page %} <li>{{ i }}</li> {% endfor %} </ul> <hr> {#循环输出页码列表#} {% for i in page.paginator.page_range %} {% if i == page.number %} {# 设置当前页的页码没有超链接 #} {{ i }} {# 页码 #} {% else %} <a href="/pag/{{ i }}">{{ i }}</a> {# 页码 #} {% endif %} {% endfor %} </body> </html>
路由:
from django.urls import path, re_path, register_converter # 导入re_path urlpatterns = [ re_path('pag/(d*)', views.pag), # 用正则设置路径为任意数字或者为空。 ]