SoFunction
Updated on 2024-12-17

Python Django simple paging implementation code analysis

This article introduces the Python Django simple paging code analysis, the text of the sample code through the introduction of the very detailed, for everyone to learn or work with certain reference learning value, you can refer to the next!

from  import models
class Book():
  title = (max_length=32)
  def __str__(self):
    return 
  class Meta:
    db_table = "books"

Batch creation of 106 data items

import os
if __name__ == '__main__':
  ("DJANGO_SETTINGS_MODULE", "")
  import django
  ()
  from app01 import models
  # 106 book objects
  objs = [(title="《Python The story of the first{}block of printing》".format(i)) for i in range(116)]
  # Batch creation in database, 10 commits at a time
  .bulk_create(objs, 10)

from  import render
from app01 import models 
def book_list(request):
  # Fetch parameters from a URL
  page_num = ("page")
  print(page_num, type(page_num))
  page_num = int(page_num)
 
  # Define two variables to hold where the data is taken from and where it is taken to
  data_start = (page_num-1)*10
  data_end = page_num*10
 
  # Total number of books
  total_count = ().count()
 
  # of data displayed per page
  per_page = 10
 
  # How many total page numbers are needed to display
  total_page, m = divmod(total_count, per_page)
  if m:
    total_page += 1 
  all_book = ()[data_start:data_end]
 
  # Pagination code for splicing html
  html_list = []
  for i in range(1, total_page+1):
    tmp = '<li><a href="/book_list/?page={0}" rel="external nofollow" >{0}</a></li>'.format(i)
    html_list.append(tmp) 
  page_html = "".join(html_list) 
  return render(request, "book_list.html", {"books": all_book, "page_html": page_html})

book_list.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>List of books</title>
  <link rel="stylesheet" href="/static/bootstrap/css/" rel="external nofollow" >
</head>
<body> 
<div class="container"> 
  <table class="table table-bordered">
    <thead>
    <tr>
      <th>serial number</th>
      <th>id</th>
      <th>reputation as calligrapher</th>
    </tr>
    </thead>
    <tbody>
    {% for book in books %}
      <tr>
        <td>{{  }}</td>
        <td>{{  }}</td>
        <td>{{  }}</td>
      </tr>
    {% endfor %} 
    </tbody>
  </table> 
  <nav aria-label="Page navigation">
    <ul class="pagination">
      {{ page_html|safe }}
    </ul>
  </nav> 
</div>
</body>
</html>

Run results:

This is the whole content of this article.