In this section, we will introduce the advanced modules provided by Django. Through the study of advanced modules, you will feel that Django is so easy to use, but at the same time it is very complex. Therefore, when learning such a heavy framework as Django, we must remember to be impatient and dare to explore new knowledge, In addition to following the progress of this tutorial, you should also take time to read more Django source code and official documents, so as to help you improve as soon as possible.
The paging function to be discussed in this section must be familiar to you. Just like the text in the textbook, if the text has a lot of content, it will be divided into many pages and displayed to the readers. This is the same as our processing data information in the development stage, because in most cases, we often face a lot of data information. In order to make the display of these information easier to read and reduce the amount of data extraction, so as to reduce the pressure on the server, we will adopt the paging processing method. Django provides developers with a built-in module Paginator class. Its usage scenarios can be seen everywhere. For example, when shopping on a treasure website, the goods on the next page are displayed, or the page numbers marked with numbers 1, 2 and 3 belong to the design of pagination.
- Understanding Paginator object properties and methods
- Paginator class constructor parameters
In this section, we first introduce the Paginator class, and finally deepen your understanding of the module through the example demonstration of the project. Paginator can be called a pager. In fact, it is also a Python class. To use it, we can introduce it in the following way:
from django.core.paginator import Paginator
This class is defined in Django core. In Paginator module, its constructor is as follows:
class Paginator: def __init__(self, object_list, per_page, orphans=0, allow_empty_first_page=True)
The meaning of each parameter is as follows:
object_list, the object list is the queried data.
per_page, the content displayed on each page, that is, the number of data pieces per page.
orphans=0. To avoid setting when the data of the last page is too small, if the data of the last page is less than this value, it will be merged into the previous page and can be omitted.
allow_empty_first_page=True, the first page is allowed to be empty, and the default is True.
2) Properties of Paginator object
We can obtain a pager object by using the following method:
paginator = Paginator(exam, 10)
Its properties are as follows:
In [1]: from django.core.paginator import Paginator #Data to be paged In [2]: objects=['a','b','c','d','e','f','g'] #Get pager object In [3]: p = Paginator(objects, 2) #Total number of objects that need classification data In [4]: p.count Out[4]: 7 #Total number of pages paged In [5]: p.num_pages Out[5]: 4 #Number of data per page In [6]: p.per_page Out[6]: 2 #The page number range after paging starts from 1, excluding 5, closed on the left and open on the right In [7]: p.page_range Out[7]: range(1, 5)
- Paginator object's method page()
Paginator pager object has only one method, page. It accepts a required parameter, namely page number, and returns a current page object. If it is not provided, it will return a TypeError error error.
In [9]: p.page() #No page number is provided and the error type is returned TypeError TypeError: page() missing 1 required positional argument: 'number' #Get the page object on page 2 In [10]: pag2=p.page(2) #Returns the current page object In [11]: pag2 Out[11]: <Page 2 of 4> #Instantiate using list In [12]: list(pag2) Out[12]: ['c', 'd']
- Common methods and properties of Page object
- Page object properties
Above, we introduced the page method of Paginator pager object. The Page() method obtains the page object of the corresponding page by passing the page number (starting from 1). This object also has its corresponding properties and methods. Let's take a look at it together:
#A list of all data objects on the current page In [14]: pag2.object_list Out[14]: ['c', 'd'] #Serial number of the current page, starting from 1, which page In [15]: pag2.number Out[15]: 2 #The Paginator object related to the current page object, which can call the original Paginator attribute In [16]: pag2.paginator Out[16]: <django.core.paginator.Paginator at 0x63b2090>
- Page object method
The adaptation method of Page object is also very simple. There is no example to explain here. Interested partners can try it on their own, as shown below:
len(): returns the number of objects on the current page.
has_next(): returns True if there is a next page.
has_previous(): returns True if there is a previous page.
has_other_pages(): returns True if there is a previous or next page.
previous_page_number(): returns the page number of the previous page. If the previous page does not exist, an InvalidPage exception is thrown.
next_page_number(): returns the page number of the next page. If the next page does not exist, an InvalidPage exception is thrown.
start_index(): returns the starting object sequence number of the current page relative to the whole list, starting from 1. As shown in the above example, 3 will be returned.
end_index(): returns the end object sequence number of the current page relative to the whole list, starting from 1 and returning 4 as shown in the above example.
Note: the Page object is an iterative object. You can use the for statement to access each object in the current Page
- Paginator's exception handling module
Paginator's exception handling module has three types, as follows:
InvalidPage: thrown when an invalid page number is passed into page().
PageNotAnInteger: thrown when a value other than an integer is passed to page().
EmptyPage: thrown when a valid value is provided to page(), but there is no object on that page, that is, the current page data is empty.
We can use the following methods to introduce and actively throw exceptions when needed in the code:
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage,InvalidPage
- Paginator instance project application
from django.shortcuts import render from index.models import Book from django.core.paginator import Paginator#Paging function #View function index / views py def page_test(request): # Test paging function books=Book.objects.all() paginator = Paginator(books,2) num_p = request.GET.get('page',1)#Take page as the key to get the default page 1 page=paginator.page(int(num_p)) return render(request,'index/page_test.html',locals())
Write page_test.html page, as follows:
<html lang="en"> <head> <meta charset="UTF-8"> <title>Paging test</title> </head> <body> {% for p in page %} <div> title:{{ p.title }} </div> {% endfor %} <!--Determine whether there is a previous page, and then splice about page Query string for--> {% if page.has_previous %} {# Get the page number of the previous page #} <a href="/index/page_test?page={{ page.previous_page_number }}">previous page</a> {% else %} previous page {% endif %} {# Cycle through the page range to select a page number #} {% for p in paginator.page_range %} {# If the page number is equal to the current page number #} {% if p == page.number %} {{ p }} {% else %} {# Otherwise, jump to the page corresponding to the page number #} <a href="/index/page_test?page={{ p }}">{{ p }}</a> {% endif %} {% endfor %} {% if page.has_next %} <a href="/index/page_test?page={{ page.next_page_number }}">next page</a> {% else %} next page {% endif %} </body> </html>
Finally, configure the route mapping relationship as 127.0.0.1:8000/index/page_test, you can access the page as follows:
Implementation of Django paging function
Figure 1: implementation of Django paging function
It can be seen that the implementation logic of the above code is mainly written in the HTML page. The attributes of the page object are used to judge whether there is a previous page or the next page, and the query string page is used to pass parameters, so as to realize the jump between various pages. Therefore, from the above code, we need to understand the Paginator object and the methods and attributes of the page object, Only in this way can Django's paging function be used freely.