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 and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software