注意,我将templates定义在项目的同级目录下: 在settings.py中配置 复制代码 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] 复制代码 urls.py 复制代码 from django.urls import path from . import views app_name='person' urlpatterns=[ path('test/', views.test), path('test/',views.test,name='test'), ] 复制代码 views.py 复制代码 from django.shortcuts import render from .models import Book from django.core.paginator import Paginator def test(request,pn=1): #获取所有的查询 book_obj=Book.objects.all() #传给paginator,每页显示两条 paginator=Paginator(book_obj,2) #pn是显示第几页,默认是第一页 page=paginator.page(pn) #将page通过context传给前端 context={'page':page} return render(request,'test/test.html',context=context) 复制代码 models.py 复制代码 class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=128,null=False) def __str__(self): return "book_title:{}".format(self.title) 复制代码 tempates/test/test.html 复制代码 Document
{% for item in page %} {% endfor %}
id title
{{item.id}} {{item.title}}
复制代码 最终效果(不要在意css,不大美观,哈哈) 在显示下网页源代码: 复制代码 Document
id title
3 java
6 zabbix从入门到精通
复制代码 总结:这是实现分页最简单的了,至于美观,可以结合bootstrap来进行美化。 技术总结:最基本的是Paginator里面的一些值(当然此处我并没有去尝试其他的,有兴趣的可以去搜下,也挺简单的)。然后其中的一个就是前端pn值如何通过url传值给后端,注意标蓝的地方。https://www.cnblogs.com/xiximayou/p/11784168.html