Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use Paginator to realize pagination in Django

Shulou Source: shulou.com Published: 2022-06-02 05:41:37 09月25日 Update

How to use Paginator to achieve pagination in Django, for this problem, this article details the corresponding analysis and solution, hoping to help more friends who want to solve this problem find a simpler and easier way.

Creating a Subject through a Model

Django models

from django.db import models

class Subject(models.Model):

"""discipline"""

no = models.AutoField(primary_key=True, verbose_name="number")

name = models.CharField(max_length=31, verbose_name="name")

intro = models.CharField(max_length=511, verbose_name="Introduction")

def __str__(self):

return self.name

class Meta:

db_table = 'tb_subject'

verbose_name_plural = "discipline"

Second, through the view module, the data to be presented to the front end

Configuration of Django view

from django.shortcuts import render

from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger

from vote.models import Subject

def show_subject(request):

"""Inquiry discipline"""

#Query all data in Subject table

subjects = Subject.objects.all().order_by("no")

#Use Paginator module to page data, 5 pieces of data per page

paginator = Paginator(subjects, 5)

#Use the request.GET.get() function to get the value of the page parameter in uri

page = request.GET.get('page')

try:

#Query whether this page is an integer and available by getting the page parameter above

subject_obj = paginator.page(page)

except PageNotAnInteger:

subject_obj = paginator.page(1)

except (EmptyPage, InvalidPage):

subject_obj = paginator.page(paginator.num_pages)

return render(request, "vote/subject.html", {'subject_list': subject_obj})

3. Render the data in view to the front-end template

front-end pagination code block

Tags: Data front end discipline question query parameter more module help answer easy easy code content function name boy partner numerical value integer Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Tech Info vpn Shulou Information OPPO Reno