This article mainly introduces the Django custom paging effect in detail, which has certain reference value. Interested friends can refer to it
Paging functionIn each Websites are necessary. For paging, it is actually to calculate the starting position of the data that should be displayed on the page in the database table based on the user's input.
Determinepaging requirements:
1. Number of data items displayed on each page
2. Number of page number links displayed on each page
3. Previous Page and next page
4. Home page and last page
Rendering:
First, use the built-in paging function of django, Write pagination class:
from django.core.paginator import Paginator, Page # 导入django分页模块 class PageInfo(object): def init(self, current_page, all_count, base_url, per_page=10, show_page=11): """ :param current_page: 当前页 :param all_count: 总页数 :param base_url: 模板 :param per_page: 每页显示数据条数 :param show_page: 显示链接页个数 """ #若url错误,默认显示第一页(错误类型可能为:空页面编号,非整数型页面编号) try: self.current_page = int(current_page) except Exception as e: self.current_page = 1 #根据数据库信息条数得出总页数 a, b = pmod(all_count, per_page) if b: a += 1 self.all_page = a self.base_url = base_url self.per_page = per_page self.show_page = show_page #当前页起始数据id def start_data(self): return (self.current_page - 1) * self.per_page #当前页结束数据id def end_data(self): return self.current_page * self.per_page #动态生成前端html def pager(self): page_list = [] half = int((self.show_page - 1)/2) #如果:总页数 < show_page,默认显示页数范围为: 1~总页数 if self.all_page < self.show_page: start_page = 1 end_page = self.all_page + 1 #如果:总页数 > show_page else: #如果:current_page - half <= 0,默认显示页数范围为:1~show_page if self.current_page <= half: start_page = 1 end_page = self.show_page + 1 else: #如果:current_page + half >总页数,默认显示页数范围为:总页数 - show_page ~ 总页数 if self.current_page + half > self.all_page: end_page = self.all_page + 1 start_page = end_page - self.show_page else: start_page = self.current_page - half end_page = self.current_page + half + 1 #首页 first_page = "<li><a href='%s?page=%s'>首页</a></li>" %(self.base_url, 1) page_list.append(first_page) #上一页(若当前页等于第一页,则上一页无链接,否则链接为当前页减1) if self.current_page <= 1: prev_page = "<li><a href='#'>上一页</a></li>" else: prev_page = "<li><a href='%s?page=%s'>上一页</a></li>" %(self.base_url, self.current_page-1) page_list.append(prev_page) #动态生成中间页数链接 for i in range(start_page, end_page): if i == self.current_page: temp = "<li class='active'><a href='%s?page=%s'>%s</a></li>" %(self.base_url, i, i) else: temp = "<li><a href='%s?page=%s'>%s</a></li>" % (self.base_url, i, i) page_list.append(temp) #下一页(若当前页等于最后页,则下一页无链接,否则链接为当前页加1) if self.current_page >= self.all_page: next_page = "<li><a href='#'>下一页</a></li>" else: next_page = "<li><a href='%s?page=%s'>下一页</a></li>" %(self.base_url, self.current_page+1) page_list.append(next_page) #末页(若总页数只有一页,则无末页标签) if self.all_page > 1: last_page = "<li><a href='%s?page=%s'>末页</a></li>" % (self.base_url, self.all_page) page_list.append(last_page) return ''.join(page_list)
Then, write the method in views (written here in app01):
from utils.pagnition import PageInfo # 从文件中导入上步自定义的分页模块 def custom(request): all_count = models.UserInfo.objects.all().count() # 获取要显示数据库的总数据条数 page_info = PageInfo(request.GET.get('page'), all_count, '/custom.html/',) # 生成分页对象 user_list = models.UserInfo.objects.all()[page_info.start_data():page_info.end_data()] # 利用分页对象获取当前页显示数据 return render(request, 'custom.html', {'user_list': user_list, 'page_info': page_info}) # 模板渲染
Then, write the "custom.html" file in the templates directory:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>customers</title> {# 引入bootstrap样式#} <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css"> </head> <body> <h1 id="customers">customers</h1> {#当前页显示的数据#} <ul> {% for row in user_list %} <li>{{ row.name }}</li> {% endfor %} </ul> {#分页#} <nav aria-label="Page navigation"> <ul class="pagination"> {# 传入page_info.pager#} {{ page_info.pager|safe }} </ul> </nav> </body> </html>
Finally, add the url relationship (urls.py):
from django.conf.urls import url from django.contrib import admin from app01 import views as app01_views urlpatterns = [ url(r'^custom.html/$', app01_views.custom), ]
At this point, you have completed customizing the paging module using django's paging function, which can be applied to different business pages.
The above is the detailed content of How to implement custom paging in Django?. For more information, please follow other related articles on the PHP Chinese website!

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor
