search
HomeBackend DevelopmentPython TutorialDjango introduction to paging examples

Django introduction to paging examples

Jun 27, 2017 am 09:54 AM
djangoPaginationcustomize

The paging function is necessary in every website. 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.

Determine the paging requirements:

1. 每页显示的数据条数
2. 每页显示页号链接数
3. 上一页和下一页
4. 首页和末页

Rendering:

First, use the built-in paging function of django, Write the paging class:

 1 from django.core.paginator import Paginator, Page      # 导入django分页模块 2  3  4 class PageInfo(object): 5     def __init__(self, current_page, all_count, base_url, per_page=10, show_page=11): 6         """ 7  8         :param current_page: 当前页 9         :param all_count: 总页数10         :param base_url: 模板11         :param per_page: 每页显示数据条数12         :param show_page: 显示链接页个数13         """14         #若url错误,默认显示第一页(错误类型可能为:空页面编号,非整数型页面编号)15         try:16             self.current_page = int(current_page)17         except Exception as e:18             self.current_page = 119         20         #根据数据库信息条数得出总页数            21         a, b = divmod(all_count, per_page)22         if b:23             a += 124         self.all_page = a   
25         26         self.base_url = base_url27         self.per_page = per_page28         self.show_page = show_page29 30     #当前页起始数据id31     def start_data(self):       
32         return (self.current_page - 1) * self.per_page33 34     #当前页结束数据id35     def end_data(self):     
36         return self.current_page * self.per_page37     38     #动态生成前端html39     def pager(self):40         page_list = []41         half = int((self.show_page - 1)/2)42         #如果:总页数  show_page47         else:48             #如果:current_page - half 总页数,默认显示页数范围为:总页数 - show_page ~ 总页数54                 if self.current_page + half > self.all_page:55                     end_page = self.all_page + 156                     start_page = end_page - self.show_page57                 else:58                     start_page = self.current_page - half59                     end_page = self.current_page + half + 160 61         #首页62         first_page = "
  • 首页
  • " %(self.base_url, 1)63         page_list.append(first_page)64 65         #上一页(若当前页等于第一页,则上一页无链接,否则链接为当前页减1)66         if self.current_page 上一页"68         else:69             prev_page = "
  • 上一页
  • " %(self.base_url, self.current_page-1)70         page_list.append(prev_page)71 72         #动态生成中间页数链接73         for i in range(start_page, end_page):74             if i == self.current_page:75                 temp = "
  • %s
  • " %(self.base_url, i, i)76             else:77                 temp = "
  • %s
  • " % (self.base_url, i, i)78             page_list.append(temp)79 80         #下一页(若当前页等于最后页,则下一页无链接,否则链接为当前页加1)81         if self.current_page >= self.all_page:82             next_page = "
  • 下一页
  • "83         else:84             next_page = "
  • 下一页
  • " %(self.base_url, self.current_page+1)85         page_list.append(next_page)86 87         #末页(若总页数只有一页,则无末页标签)88         if self.all_page > 1:89             last_page = "
  • 末页
  • " % (self.base_url, self.all_page)90             page_list.append(last_page)91 92         return ''.join(page_list)

    Then, write the method in views (written here in app01):

    1 from utils.pagnition import PageInfo    # 从文件中导入上步自定义的分页模块2 3 def custom(request):4     all_count = models.UserInfo.objects.all().count()   # 获取要显示数据库的总数据条数5     page_info = PageInfo(request.GET.get('page'), all_count, '/custom.html/',)      # 生成分页对象6     user_list = models.UserInfo.objects.all()[page_info.start_data():page_info.end_data()]      # 利用分页对象获取当前页显示数据7     return render(request, 'custom.html', {'user_list': user_list, 'page_info': page_info})     # 模板渲染

    Then, in templates Write the "custom.html" file in the directory:

     1 nbsp;html> 2  3  4     <meta> 5     <title>customers</title> 6 {#    引入bootstrap样式#} 7     <link> 8  9 10 <h1 id="customers">customers</h1>11 {#当前页显示的数据#}12 
      13     {% for row in user_list %}14         
    • {{ row.name }}
    • 15     {% endfor %}16 
    17 18 {#分页#}19     25 26 27 

    Finally, add the url relationship (urls.py):

    1 from django.conf.urls import url2 from django.contrib import admin3 from app01 import views as app01_views4 5 urlpatterns = [6     url(r'^custom.html/$', app01_views.custom),7 ]

    At this point, This completes the custom paging module using Django's paging function, which can be applied to different business pages.

    Reference materials:

    1. The Road to Python [Part 17]: Django [Advanced Chapter]

    The above is the detailed content of Django introduction to paging examples. 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

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    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

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    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.

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools