search
HomeBackend DevelopmentPython TutorialHow to implement custom paging in Django?

How to implement custom paging in Django?

Jun 29, 2017 pm 03:31 PM
djangoaccomplishcustomize

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=&#39;%s?page=%s&#39;>首页</a></li>" %(self.base_url, 1)
  page_list.append(first_page)

  #上一页(若当前页等于第一页,则上一页无链接,否则链接为当前页减1)
  if self.current_page <= 1:
   prev_page = "<li><a href=&#39;#&#39;>上一页</a></li>"
  else:
   prev_page = "<li><a href=&#39;%s?page=%s&#39;>上一页</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=&#39;active&#39;><a href=&#39;%s?page=%s&#39;>%s</a></li>" %(self.base_url, i, i)
   else:
    temp = "<li><a href=&#39;%s?page=%s&#39;>%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=&#39;#&#39;>下一页</a></li>"
  else:
   next_page = "<li><a href=&#39;%s?page=%s&#39;>下一页</a></li>" %(self.base_url, self.current_page+1)
  page_list.append(next_page)

  #末页(若总页数只有一页,则无末页标签)
  if self.all_page > 1:
   last_page = "<li><a href=&#39;%s?page=%s&#39;>末页</a></li>" % (self.base_url, self.all_page)
   page_list.append(last_page)

  return &#39;&#39;.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(&#39;page&#39;), all_count, &#39;/custom.html/&#39;,)  
 # 生成分页对象
 user_list = models.UserInfo.objects.all()[page_info.start_data():page_info.end_data()]  
 # 利用分页对象获取当前页显示数据
 return render(request, &#39;custom.html&#39;, {&#39;user_list&#39;: user_list, &#39;page_info&#39;: 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&#39;^custom.html/$&#39;, 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

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.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

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

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

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

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

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

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

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

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SecLists

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

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

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

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor