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 turn the page with Django

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail how to turn the page on Django. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

1. Views module imports Paginator class to realize data paging

ApiTest/apiviews.py

Each line is commented in the hope that it will help you understand.

From django.shortcuts import renderfrom ApiTest.models import ApiTestfrom django.contrib.auth.decorators import login_requiredfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger, InvalidPage@login_requireddef api_test_manage (request): username = request.session.get ('user',') # get all interface test data apitest_list = ApiTest.objects.all (). Order_by ('id') # generate Paginator object to paging data Display 10 pieces of data per page paginator = Paginator (apitest_list,10) # use the request.GET.get () function to get the value of the page parameter in url. The default page 1 page = request.GET.get ('page', 1) # converts the current page number obtained to the integer type current_page = int (page) try: # to get the interface data list of the query page number, and the page () function determines whether the page argument is a valid number. The source code of the page () function is attached at the end of the article apitest_list = paginator.page (page) except PageNotAnInteger: apitest_list = paginator.page (1) except (EmptyPage, InvalidPage): # paginator.num_pages apitest_list = paginator.page (paginator.num_pages) return render (request, "apitest_manage.html", {'user': username,' apitests': apitest_list}) 2. Render the views data to the front-end template

Just add this code to the corresponding html file.

{# previous page link #} {% if apitests.has_previous%} previous page {% else%} previous page {% endif%} {# intermediate numbers show #} {% for num in apitests.paginator.page_range%} {% if num = = currentPage%} {{num}} {% else%} {{num}} {% endif%} {% endfor%} {# next page link #} {% if apitests.has_next%} {# if there is a next page Then the next page is displayed normally, link #} next page {% else%} next page {% endif%} 3. Effect display

Fourth, the source code of Paginator class

This class is mainly used in views files

Class Paginator: def _ init__ (self, object_list, per_page, orphans=0, allow_empty_first_page=True): self.object_list = object_list self._check_object_list_is_ordered () self.per_page = int (per_page) self.orphans = int (orphans) self.allow_empty_first_page = allow_empty_first_page def validate_number (self Number): "Validate the given 1-based page number." Try: if isinstance (number, float) and not number.is_integer (): raise ValueError number = int (number) except (TypeError, ValueError): raise PageNotAnInteger (_ ('That page number is not an integer')) if number

< 1: raise EmptyPage(_('That page number is less than 1')) if number >

Self.num_pages: if number = = 1 and self.allow_empty_first_page: pass else: raise EmptyPage (_ ('That page contains no results')) return number def get_page (self, number): "Return a valid page, even if the page argument isn't a number or isn't in range." Try: number = self.validate_number (number) except PageNotAnInteger: number = 1 except EmptyPage: number = self.num_pages return self.page (number) def page (self, number): "" Return a Page object for the given 1-based page number. " Number = self.validate_number (number) bottom = (number-1) * self.per_page top = bottom + self.per_page if top + self.orphans > = self.count: top = self.count return self._get_page (self.object_ list [bo ttom:top], number, self) def _ get_page (self, * args, * * kwargs): "" Return an instance of a single page. This hook can be used by subclasses to use an alternative to the standard: cls: `Page` object. " Return Page (* args, * * kwargs) @ cached_property def count (self): "Return the total number of objects, across all pages." C = getattr (self.object_list, 'count', None) if callable (c) and not inspect.isbuiltin (c) and method_has_no_args (c): return c () return len (self.object_list) @ cached_property def num_pages (self): "" Return the total number of pages. "" If self.count = = 0 and not self.allow_empty_first_page: return 0 hits = max (1, self.count-self.orphans) return ceil (hits / self.per_page) @ property def page_range (self): "Return a 1-based range of pages for iterating through within a template for loop." Return range (1, self.num_pages + 1) def _ check_object_list_is_ordered (self): "Warn if self.object_list is unordered (typically a QuerySet)." Ordered = getattr (self.object_list, 'ordered', None) if ordered is not None and not ordered: obj_list_repr = (' {} {} '.format (self.object_list.model, self.object_list.__class__.__name__) if hasattr (self.object_list) 'model') else' {! r} '.format (self.object_list) warnings.warn (' Pagination may yield inconsistent results with an unordered''object_list: {}.' .format (obj_list_repr), UnorderedObjectListWarning, stacklevel=3) V, Page class source code

This class is mainly used in html files

Class Page (collections.abc.Sequence): def _ init__ (self, object_list, number, paginator): self.object_list = object_list self.number = number self.paginator = paginator def _ repr__ (self): return'% (self.number, self.paginator.num_pages) def _ len__ (self): return len (self.object_list) def _ getitem__ (self) Index): if not isinstance (index, (int, slice)): raise TypeError ('Page indices must be integers or slices, not% s.'% type (index). _ _ name__) # The object_list is converted to a list so that if it was a QuerySet # it won't be a database hit per _ _ getitem__. If not isinstance (self.object_list, list): self.object_list = list (self.object_list) return self.object_ list [index] def has_next (self): return self.number

< self.paginator.num_pages def has_previous(self): return self.number >

1 def has_other_pages (self): return self.has_previous () or self.has_next () def next_page_number (self): return self.paginator.validate_number (self.number + 1) def previous_page_number (self): return self.paginator.validate_number (self.number-1) def start_index (self): "" Return the 1-based index of the first object on this page Relative to total objects in the paginator. # Special case, return zero if no items. If self.paginator.count = = 0: return 0 return (self.paginator.per_page * (self.number-1)) + 1 def end_index (self): "" Return the 1-based index of the last object on this page, relative to total objects found (hits). "" # Special case for the last page because there can be orphans. If self.number = = self.paginator.num_pages: return self.paginator.count return self.number * self.paginator.per_page 's article on "how to turn the page with Django" ends here. I hope the above content can be of some help to you, so that you can learn more knowledge. If you think the article is good, please share it for more people to see.

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

Development

Wechat

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

12
Report