Pagination refers to paging in web The page has a lot of data to display , For the convenience of reading, only part of the data is displayed in each page . The advantage is that it is easy to read and reduce the amount of data extraction , Reduce server pressure .
Django Provides Paginator Class can easily implement the paging function .Paginator Class is located ’django.core.paginator’ Module .
Responsible for the overall management of paging data .
paginator = Paginator(object_list, per_page)
Parameters :
Return value :
Paginator The object of
Parameters number Page number information ( from 1 Start );
Returns the current number Also corresponding page information ;
If the page number provided does not exist , Throw out Invalidpage abnormal , Contains two unusual subclasses :
Manage a page of data .
Paginator Object's page() Method returns page object .
page = Paginator.page( Page number )
example :
(a)views.py
def test_page(request):
# /test_page/4
# /test_page?page=1
page_num = request.GET.get('page', 1)
all_data = ['a', 'b', 'c', 'd', 'e']
# initialization paginator
paginator = Paginator(all_data, 2)
# Initialize the specific page number page object
c_page = paginator.page(int(page_num))
return render(request, 'test_page.html', locals())
(b)urls.py
urlpatterns = [
path('admin/', admin.site.urls),
# path('test_mw/', views.test_mw),
path('test_csrf', views.test_csrf),
path('test_page', views.test_page),
]
(c)template.test_page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Pagination </title>
</head>
<body>
<!-- <a href="/make_page_csv?page={
{ c_page.number }}"> Generate </a> -->
{% for p in c_page %}
<p>{
{ p }}</p>
{% endfor %}
{% if c_page.has_previous %}
<a href="/test_page?page={
{ c_page.previous_page_number }}"> The previous page </a>
{% else %}
The previous page
{% endif %}
{% for p_num in paginator.page_range %}
{% if p_num == c_page.number %}
{
{ p_num }}
{% else %}
<a href="/test_page?page={
{ p_num }}">{
{ p_num }}</a>
{% endif %}
{% endfor %}
{% if c_page.has_next %}
<a href="/test_page?page={
{ c_page.next_page_number }}"> The next page </a>
{% else %}
The next page
{% endif %}
</body>
</html>
visit :http://192.168.28.128:8000/test_page