Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Paginator to realize pagination in Django

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report