Home Backend Development Python Tutorial How to implement custom paging in Django?

How to implement custom paging in Django?

Jun 29, 2017 pm 03:31 PM
django accomplish customize

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)
Copy after login

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}) 
 # 模板渲染
Copy after login

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>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>
Copy after login

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),
 ]
Copy after login

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 of this Website
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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to quickly set up a custom avatar in Netflix How to quickly set up a custom avatar in Netflix Feb 19, 2024 pm 06:33 PM

An avatar on Netflix is ​​a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

The operation process of edius custom screen layout The operation process of edius custom screen layout Mar 27, 2024 pm 06:50 PM

1. The picture below is the default screen layout of edius. The default EDIUS window layout is a horizontal layout. Therefore, in a single-monitor environment, many windows overlap and the preview window is in single-window mode. 2. You can enable [Dual Window Mode] through the [View] menu bar to make the preview window display the playback window and recording window at the same time. 3. You can restore the default screen layout through [View menu bar>Window Layout>General]. In addition, you can also customize the layout that suits you and save it as a commonly used screen layout: drag the window to a layout that suits you, then click [View > Window Layout > Save Current Layout > New], and in the pop-up [Save Current Layout] Layout] enter the layout name in the small window and click OK

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

How to implement exact division operation in Golang How to implement exact division operation in Golang Feb 20, 2024 pm 10:51 PM

Implementing exact division operations in Golang is a common need, especially in scenarios involving financial calculations or other scenarios that require high-precision calculations. Golang's built-in division operator "/" is calculated for floating point numbers, and sometimes there is a problem of precision loss. In order to solve this problem, we can use third-party libraries or custom functions to implement exact division operations. A common approach is to use the Rat type from the math/big package, which provides a representation of fractions and can be used to implement exact division operations.

See all articles