原理步骤参考:
Django开发_14_后台管理及分页器-CSDN博客
一、创建Django项目
二、创建page_app
python manage.py startapp page_app
三、修改settings.py文件
(一)添加app
(二)设置每页显示数据个数
(三)设置中文显示
四、总路由添加子路由路径
from django.contrib import admin
from django.urls import path, includeurlpatterns = [path("admin/", admin.site.urls),path("",include("page_app.urls",namespace="page"))
]
五、添加子路由文件
from django.urls import pathapp_name = "page"
urlpatterns = []
六、models.py:创建模型
from django.db import modelsclass Student(models.Model):name = models.CharField(max_length=32, verbose_name="姓名")gender = models.CharField(max_length=2, verbose_name="性别")score = models.FloatField(verbose_name="成绩")def __str__(self):return self.name # 添加实例化对象时以姓名显示class Meta:verbose_name = "学生" # 后台管理显示中文:学生verbose_name_plural = verbose_name # 用于后台管理复数形式不显示s@classmethoddef get_list(cls, **kwargs):filters = {}return cls.objects.filter(**filters) # 没有参数相当于cls.objects.all()
迁移模型:
manage.py makemigrations
python manage.py migrate
七、admin.py:注册模型
from django.contrib import adminfrom page_app.models import Studentmodels = [Student
]admin.site.register(models)
八、登录admin后台添加实例化模型
(一)创建超级账号
(二)启动运行
(三)登录添加学生
九、views.py:编写视图函数
from django.shortcuts import render
from django.core.paginator import Paginator, InvalidPagefrom Paginator.settings import PAGE_SIZE
from page_app.models import Studentdef list_students_view(request):page_num = request.GET.get("page", 1) # href中没有传递page时默认为1students = Student.get_list()paginator = Paginator(students, PAGE_SIZE)try:data = paginator.page(page_num)except InvalidPage:data = paginator.page(1)return render(request, "stu.html", locals())
十、urls.py:路由设置
from django.urls import pathfrom page_app.views import list_students_viewapp_name = "page"
urlpatterns = [path("list/", list_students_view, name="list")
]
十一、html文件:上一页、下一页以及显示当前页/总页数
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>分页</title>
</head>
<body>
<table><thead><tr><th>学号</th><th>姓名</th><th>性别</th><th>成绩</th></tr></thead><tbody>{% for i in data %}<tr><td>{{ i.id }}</td><td>{{ i.name }}</td><td>{{ i.gender }}</td><td>{{ i.score }}</td></tr>{% endfor %}</tbody>
</table>
<center>{% if data.has_previous %}<a href="{% url 'page:list' %}?page={{ data.previous_page_number }}">上一页</a>{% else %}<a href="">上一页</a>{% endif %}{{ page_num }}/{{ paginator.num_pages }}{% if data.has_next %}<a href="{% url 'page:list' %}?page={{ data.next_page_number }}">下一页</a>{% else %}<a href="">下一页</a>{% endif %}</center>
</body>
</html>
十二、启动运行,效果展示
http://127.0.0.1:8000/list/