Do you know the usage of Django pager

Time:2021-12-8
catalogue
  • 1. Prepare basic data
  • 2. One time display data
  • 3. Introducing a pager

DjangoIs a large and comprehensive framework. It should be made clear that the paging data obtained by transferring parameters is generally sent to the servergetIt is implemented in the form of request. When sending the view data to the back-end service, it can carry one or more parameters and send themgetRequest to implement paging view function

As summarized earlierdrfThe use of pager in the framework is mainly introduced in this paperDjangodevelopmentMVTUse of pagers in model projects

1. Prepare basic data

Design table model

In order to reflect the effect of paging, you need to create a table and prepare more data. The model is as follows

?
1
2
3
4
5
6
7
from django.db import models
 
# Create your models here.
 
class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=9, decimal_places=2# 9999999.99

After database migration, design a view function to insert data into this table in batches by triggering the view function

DjangoMedium utilizationormThere are generally two ways to realize batch insertion: single insertion or utilizationbulk_createBatch insert

Final translation intosqlStatements are similar to multiple statementsinsertStatement and oneinsertDifferences between

?
1
2
3
4
5
6
7
8
9
10
11
12
13
def create_book(request):
 
    #Batch insertion method I
    for i in range(100):
        Book.objects.create(title="book"+str(i),price=i*i)
        #Batch insertion mode 2
    book_list = []
    for i in range(100):
        book = Book(title="book"+str(i),price=i*i)
        book_list.append(book)
    Book.objects.bulk_create(book_list)
    
    return HttpResponse("Added successfully")

2. One time display data

Next, the data is displayed to the front-end page at one time through the template syntax

The view functions are as follows

?
1
2
3
def get_books(request):
    book_list = Book.objects.all()
    return render(request, "index.html", {"book_list": book_list})

Template pageindex.htmlas follows

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul>
    {% for book in book_list %}
    <li>{ book.title } : { book.price }</li>
    {% endfor %}
</ul>
</body>
</html>

At this time, a one-time visit shows all the informationbook

3. Introducing a pager

After the pager is introduced, you can perform related operations on global paging objects and single page objects, including related syntax

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#Introducing a pager
from django.core.paginator import Paginator
 
        ...
    #Global pager object
    paginator = Paginator([1,2,3,4,5,6,7,8,9,10],3)
    print(paginator.count) # 10   Total data
    print(paginator.num_pages)  # 4   PageCount
    print(paginator.page_range) # range(1, 5)   List of page numbers
 
    #Single page object
    page = paginator.page(2)
    print(page.has_next())  #Next page
    print(page.next_page_number())  #Write a page number
    print(page.has_previous())  #Is there a previous page
    print(page.previous_page_number())  #Page number of previous page
    #Fetches the value of a single page object
    print(page.object_list) # [4, 5, 6]
    for i in page:
       print(i)

In this example, the pager and template syntax are used, such as fetching each page8Get the number of page number conditions given by the user and return the data of the corresponding page. By default, the data of the first page is returned when no conditions are given

?
1
2
3
4
5
6
7
8
from django.core.paginator import Paginator
   #Take out the page number of the current user
   current_num = int(request.GET.get("page", 1))
   book_list = Book.objects.all()
   paginator = Paginator(book_list, 8)
   page = paginator.page(current_num)
  
   return render(request,"index.html",{"page":page})

Finally, you can usebootstrapThe component adds a page turning button in the page template. The button deepens in the current page. Clicking is prohibited when there is no previous page

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
...
<body>
 
<ul>
    {% for book in page %}
    <li>{ book.title } : { book.price }</li>
    {% endfor %}
</ul>
<nav aria-label="Page navigation">
  <ul class="pagination">
    {% if page.has_previous %}
    <li>
      <a href="/?page={ page.previous_page_number }" rel="external nofollow"  aria-label="Previous">
        <span aria-hidden="true">Previous page</span>
      </a>
    </li>
    {% else %}
    <li class="disabled">
      <a href="#" rel="external nofollow"  rel="external nofollow"  aria-label="Previous">
        <span aria-hidden="true">Previous page</span>
      </a>
    </li>
    {% endif %}
      {% for num in page_range %}
      {% if num == current_num %}
          <li class="active"><a href="/?page={ num }" rel="external nofollow"  rel="external nofollow" >{ num }</a></li>
      {% else %}
          <li><a href="/?page={ num }" rel="external nofollow"  rel="external nofollow" >{ num }</a></li>
      {% endif %}
      {% endfor %}
    <li>
      <a href="#" rel="external nofollow"  rel="external nofollow"  aria-label="Next">
        <span aria-hidden="true">Next page</span>
      </a>
    </li>
  </ul>
</nav>
</body>
...

In the view function: handle related exceptions; Transfer relevant parameters; When there are many page numbers, only part of the page numbers are displayed, for example, when there are most, the total page numbers are displayed10Page number, and the current page number is always displayed in the middle; Handle boundary cases, negative page numbers and maximum page numbers used up separately

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.core.paginator import Paginator
        ...
    #Take out the page number of the current user
    current_num = int(request.GET.get("page", 1))
    book_list = Book.objects.all()
    paginator = Paginator(book_list, 8)
    page = paginator.page(current_num)
 
    #When greater than 11 pages
    if paginator.num_pages > 11:
        #When the last 5 pages of the current page number exceed the maximum page number, the last 10 items are displayed
        if current_num + 5 > paginator.num_pages:
            page_range = range(paginator.num_pages - 10, paginator.num_pages + 1)
        #When the first 5 pages of the current page number are negative, the first 10 items are displayed
        elif current_num - 5 < 1:
            page_range = range(1, 12)
        else:
            #Displays page numbers from 5 left to 5 right pages
            page_range = range(current_num - 5, current_num + 5 + 1)
    #Show all page numbers when less than 11 pages
    else:
        page_range = paginator.page_range
 
    return render(request, "index.html", {"page": page, "paginator": paginator, "current_num": current_num, "page_range": page_range})

The above is the usage of Django pager. Do you understand it? For more information about Django pager, please pay attention to other related articles of developeppaper!

Recommended Today

SAP commerce cloud smartedit learning notes

Official documents Smartedit is a pluggable JavaScript framework with a UI that enables developers to manage existing web pages. The smartedit ecosystem consists of modules and extensions that jointly provide smartedit products. Smartedit is a front-end driven scalable application in the smartedit module. The sap commerce cloud implementation of CMS rest calls is part of […]