我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.core.paginator.InvalidPage()。
def render(self, context): key = self.queryset_var.var value = self.queryset_var.resolve(context) if isinstance(self.paginate_by, int): paginate_by = self.paginate_by else: paginate_by = self.paginate_by.resolve(context) paginator = Paginator(value, paginate_by, self.orphans) try: page_obj = paginator.page(context['request'].page) except InvalidPage: if INVALID_PAGE_RAISES_404: raise Http404('Invalid page requested. If DEBUG were set to ' + 'False, an HTTP 404 page would have been shown instead.') context[key] = [] context['invalid_page'] = True return '' if self.context_var is not None: context[self.context_var] = page_obj.object_list else: context[key] = page_obj.object_list context['paginator'] = paginator context['page_obj'] = page_obj return ''
def paginate_queryset(self, queryset, page_size): """ Paginate the queryset, if needed. """ paginator = self.get_paginator( queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty()) page_kwarg = self.page_kwarg page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 try: page_number = int(page) except ValueError: if page == 'last': page_number = paginator.num_pages else: raise Http404(_("Page is not 'last', nor can it be converted to an int.")) try: page = paginator.page(page_number) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage as e: raise Http404(_('Invalid page (%(page_number)s): %(message)s') % { 'page_number': page_number, 'message': str(e) })
def _get_pagination(objects_list, request): paginator = Paginator(objects_list, 20) try: page = int(request.GET.get('page', '1')) except: page = 1 try: objects = paginator.page(page) except(EmptyPage, InvalidPage): objects = paginator.page(1) # page_range to show at bottom of table index = objects.number - 1 max_index = len(paginator.page_range) start_index = index - 4 if index >= 4 else 0 end_index = index + 4 if index <= max_index - 4 else max_index page_range = paginator.page_range[start_index:end_index] return objects, page_range # Status Page
def image_viewer(request: HttpRequest, archive: int, page: int) -> HttpResponse: images = Image.objects.filter(archive=archive, extracted=True) if not images: raise Http404("Archive " + str(archive) + " has no extracted images") paginator = Paginator(images, 1) try: image = paginator.page(page) except (InvalidPage, EmptyPage): image = paginator.page(paginator.num_pages) image_object = image.object_list[0] if image_object.image_width / image_object.image_height > 1: image_object.is_horizontal = True d = {'image': image, 'backurl': redirect(image.object_list[0].archive).url, 'images_range': range(1, images.count() + 1), 'image_object': image_object} return render(request, "viewer/image_viewer.html", d)
def list_guazi(request): after_range_num = 5 before_range_num = 4 page_size = 20 Guazi_list = GuaziCar.objects.all().order_by('-id') paginator = Paginator(Guazi_list, page_size) try: page = int(request.GET.get('page','1')) if page < 1: page=1 except ValueError: page=1 try: carlist = paginator.page(page) except (EmptyPage,InvalidPage,PageNotAnInteger): carlist = paginator.page(1) if page >= after_range_num: page_range = list(paginator.page_range)[page-after_range_num:page+before_range_num] else: page_range = list(paginator.page_range)[0:int(page)+before_range_num] return render(request, 'guazi.html', {'guazi_list': carlist, 'page_range': page_range})
def get_page(self, data): try: page_no = int(self.request.GET.get(self.page_attribute_name, 1)) except (TypeError, ValueError): raise NotFound('Invalid page number.') if page_no < 1: raise NotFound('Page number should be 1 or greater.') # Explicitly evaluate data before sending it to Paginator, otherwise # (at least in the case of RelatedSearchQuerySet) the total count # goes completely wrong # see: https://github.com/django-haystack/django-haystack/issues/362 data[:self.results_per_page] paginator = Paginator(data, self.results_per_page) try: page = paginator.page(page_no) except InvalidPage: raise NotFound('No such page!') return page
def results(request, template_name="search/results.html"): """ template for displaying settings.PRODUCTS_PER_PAGE paginated product results """ # get current search phrase q = request.GET.get('q', '') # get current page number. Set to 1 is missing or invalid try: page = int(request.GET.get('page', 1)) except ValueError: page = 1 matching = search.products(q).get('products', []) # generate the pagintor object paginator = Paginator(matching, settings.PRODUCTS_PER_PAGE) try: results = paginator.page(page).object_list except (InvalidPage, EmptyPage): results = paginator.page(1).object_list search.store(request, q) page_title = 'Search Results for: ' + q return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def paginate_dataset(self, dataset, page_size): paginator = self.get_paginator( dataset, page_size, orphans=0, allow_empty_first_page=True) page_kwarg = self.page_kwarg page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg)\ or 1 try: page_number = int(page) except ValueError: raise Http404(_('Page cannot be converted to an int.')) try: page = paginator.page(page_number) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage as e: raise Http404(_('Invalid page (%(page_number)s): %(message)s') % { 'page_number': page_number, 'message': str(e) })
def render(self, context): key = self.queryset_var.var value = self.queryset_var.resolve(context) if isinstance(self.paginate_by, int): paginate_by = self.paginate_by else: paginate_by = self.paginate_by.resolve(context) paginator = Paginator(value, paginate_by, self.orphans) try: page_obj = paginator.page(context['request'].page) except InvalidPage: if INVALID_PAGE_RAISES_404: raise Http404('Invalid page requested. If DEBUG were set to ' + 'False, an HTTP 404 page would have been shown instead.') context[key] = [] context['invalid_page'] = True return u'' if self.context_var is not None: context[self.context_var] = page_obj.object_list else: context[key] = page_obj.object_list context['paginator'] = paginator context['page_obj'] = page_obj return u''
def getmovielistbystyle(request,page=1): after_range_num =5 before_range_num=4 try: page=int(page) if page<1: page=1 except ValueError: page=1 style = request.GET.get('style') movie_list = Movie.objects.filter(style__contains=u'??') paginator = Paginator(movie_list,12) try: movielist = paginator.page(page) except(EmptyPage,InvalidPage,PageNotAnInteger): movielist=paginator.page(1) if page>=after_range_num: page_range=paginator.page_range[page-after_range_num:page+before_range_num] else: page_range = paginator.page_range[0:int(page)+before_range_num] return render(request,'movie/allfilms.html',locals()) #??????
def route_view(request): """ Display a list of global routing table entries which match resources listed in received certificates. """ conf = get_conf(request.user, request.session['handle']) count = request.GET.get('count', 25) page = request.GET.get('page', 1) paginator = Paginator(conf.routes, count) try: routes = paginator.page(page) except InvalidPage: # page was empty, or page number was invalid routes = [] ts = dict((attr['name'], attr['ts']) for attr in models.Timestamp.objects.values()) return render(request, 'app/routes_view.html', {'routes': routes, 'timestamp': ts})
def indexPaginator(request,id): """ ????? ?????????? ???????? ????? ????????? """ try: page_num = request.GET['page'] except KeyError: page_num = 1 cats = Category.objects.all().order_by('name') if id == None: cat = Category.objects.first() else: cat = Category.objects.get(pk=id) paginator = Paginator(Good.objects.filter(category=cat).order_by('name'),1) try: goods = paginator.page(page_num) except InvalidPage: goods = paginator.page(1) return render(request, "indexPaginator.html", {"category":cat,"cats":cats,"goods":goods})
def blogindex(request): # need to add pagination etc. blog_posts = Post.objects.published() paginator = Paginator(blog_posts, 5) pagenum = request.GET.get('page', 1) max_page = paginator.num_pages, try: page = paginator.page(pagenum) except (EmptyPage, InvalidPage): raise Http404 paginator_html = make_paginator_text('/blogindex/?', int(pagenum), max_page[0]) return render_to_response( 'publicsite_redesign/blogindex.html', {'post_list': page.object_list, 'paginator_html':paginator_html, } )
def blogtag(request, term): if len(term)<3: raise Http404 blog_posts = Post.objects.term(term) paginator = Paginator(blog_posts, 5) pagenum = request.GET.get('page', 1) max_page = paginator.num_pages, try: page = paginator.page(pagenum) except (EmptyPage, InvalidPage): raise Http404 paginator_html = make_paginator_text('/blog/tag/' + term + '/?', int(pagenum), max_page[0]) page_title = "Posts tagged '%s' - page %s of %s" % (term, pagenum, max_page[0]) return render_to_response( 'publicsite_redesign/blogindex.html', {'post_list': page.object_list, 'paginator_html':paginator_html, 'page_title':page_title, } )
def bydate(request,start,end): docset = Event.objects.daterange(start, end) paginator = Paginator(docset, 25, orphans=5) pagenum = request.GET.get('page', 1) try: page = paginator.page(pagenum) except (EmptyPage, InvalidPage): raise Http404 return render_to_response( 'publicsite/snapshot.html', {'snapshot_image_name': '', 'page': page, } ) # # widgets #
def paginate_queryset(self, queryset, page_size): """ Paginate the queryset, if needed. """ paginator = self.get_paginator( queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty()) page_kwarg = self.page_kwarg page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 try: page_number = int(page) except ValueError: raise Http404(_("Page can not be converted to an int.")) try: page = paginator.page(page_number) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage as e: raise Http404(_('Invalid page (%(page_number)s): %(message)s') % { 'page_number': page_number, 'message': str(e) })
def paginate(self): records = self.report.results self.paginator = self.report.get_paginator() result_count = self.paginator.count self.multi_page = result_count > self.report.get_list_per_page() self.can_show_all = result_count <= self.report.get_list_max_show_all() if not (self.show_all and self.can_show_all) and self.multi_page: try: records = self.paginator.page(self.page_num + 1).object_list except InvalidPage: raise IncorrectLookupParameters return records
def pages(post_objects, request): """ page public function , return page's object tuple ???????????????? """ paginator = Paginator(post_objects, 20) try: current_page = int(request.GET.get('page', '1')) except ValueError: current_page = 1 page_range = page_list_return(len(paginator.page_range), current_page) try: page_objects = paginator.page(current_page) except (EmptyPage, InvalidPage): page_objects = paginator.page(paginator.num_pages) if current_page >= 5: show_first = 1 else: show_first = 0 if current_page <= (len(paginator.page_range) - 3): show_end = 1 else: show_end = 0 # ????? ???? ????? ????? ????????????????????? return post_objects, paginator, page_objects, page_range, current_page, show_first, show_end
def get_results(self, request): paginator = self.model_admin.get_paginator(request, self.queryset, self.list_per_page) # Get the number of objects, with admin filters applied. result_count = paginator.count # Get the total number of objects, with no admin filters applied. # Perform a slight optimization: # full_result_count is equal to paginator.count if no filters # were applied if self.model_admin.show_full_result_count: if self.get_filters_params() or self.params.get(SEARCH_VAR): full_result_count = self.root_queryset.count() else: full_result_count = result_count else: full_result_count = None can_show_all = result_count <= self.list_max_show_all multi_page = result_count > self.list_per_page # Get the list of objects to display on this page. if (self.show_all and can_show_all) or not multi_page: result_list = self.queryset._clone() else: try: result_list = paginator.page(self.page_num + 1).object_list except InvalidPage: raise IncorrectLookupParameters self.result_count = result_count self.show_full_result_count = self.model_admin.show_full_result_count # Admin actions are shown if there is at least one entry # or if entries are not counted because show_full_result_count is disabled self.show_admin_actions = not self.show_full_result_count or bool(full_result_count) self.full_result_count = full_result_count self.result_list = result_list self.can_show_all = can_show_all self.multi_page = multi_page self.paginator = paginator
def get_results(self, request): paginator = self.model_admin.get_paginator(request, self.queryset, self.list_per_page) # Get the number of objects, with admin filters applied. result_count = paginator.count # Get the total number of objects, with no admin filters applied. if self.model_admin.show_full_result_count: full_result_count = self.root_queryset.count() else: full_result_count = None can_show_all = result_count <= self.list_max_show_all multi_page = result_count > self.list_per_page # Get the list of objects to display on this page. if (self.show_all and can_show_all) or not multi_page: result_list = self.queryset._clone() else: try: result_list = paginator.page(self.page_num + 1).object_list except InvalidPage: raise IncorrectLookupParameters self.result_count = result_count self.show_full_result_count = self.model_admin.show_full_result_count # Admin actions are shown if there is at least one entry # or if entries are not counted because show_full_result_count is disabled self.show_admin_actions = not self.show_full_result_count or bool(full_result_count) self.full_result_count = full_result_count self.result_list = result_list self.can_show_all = can_show_all self.multi_page = multi_page self.paginator = paginator
def get_paginator_items(items, paginate_by, page_number): if not page_number: page_number = 1 paginator = Paginator(items, paginate_by) try: page_number = int(page_number) except ValueError: raise Http404('Page can not be converted to an int.') try: items = paginator.page(page_number) except InvalidPage as err: raise Http404('Invalid page (%(page_number)s): %(message)s' % { 'page_number': page_number, 'message': str(err)}) return items
def paginate_results(results, get_data, paginate_by=25): paginator = Paginator(results, paginate_by) page_number = get_data.get('page', 1) try: page = paginator.page(page_number) except InvalidPage: raise Http404('No such page!') return page
def view_changes(request, username=None, revision_id=None, object_id=None): """Recent changes""" boring_models = [LanguageListOrder, LanguageList, MeaningList] boring_model_ids = [ContentType.objects.get_for_model(m).id for m in boring_models] def interesting_versions(self): return self.version_set.exclude(content_type_id__in=boring_model_ids) Revision.add_to_class("interesting_versions", interesting_versions) if not username: recent_changes = Revision.objects.all().order_by("-id") else: recent_changes = Revision.objects.filter( user__username=username).order_by("-id") paginator = Paginator(recent_changes, 50) try: # Make sure page request is an int. If not, deliver first page. page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: # If page request is out of range, deliver last page of results. changes = paginator.page(page) except (EmptyPage, InvalidPage): changes = paginator.page(paginator.num_pages) userIds = set(Revision.objects.values_list("user", flat=True).distinct()) contributors = sorted([(User.objects.get(id=user_id), Revision.objects.filter(user=user_id).count()) for user_id in userIds if user_id is not None], key=lambda x: -x[1]) return render_template(request, "view_changes.html", {"changes": changes, "contributors": contributors})
def make_result_list(self): # Get search parameters from the query string. self.base_queryset = self.queryset() self.list_queryset = self.get_list_queryset() self.ordering_field_columns = self.get_ordering_field_columns() self.paginator = self.get_paginator() # Get the number of objects, with admin filters applied. self.result_count = self.paginator.count # Get the total number of objects, with no admin filters applied. # Perform a slight optimization: Check to see whether any filters were # given. If not, use paginator.hits to calculate the number of objects, # because we've already done paginator.hits and the value is cached. if not self.list_queryset.query.where: self.full_result_count = self.result_count else: self.full_result_count = self.base_queryset.count() self.can_show_all = self.result_count <= self.list_max_show_all self.multi_page = self.result_count > self.list_per_page # Get the list of objects to display on this page. if (self.show_all and self.can_show_all) or not self.multi_page: self.result_list = self.list_queryset._clone() else: try: self.result_list = self.paginator.page( self.page_num + 1).object_list except InvalidPage: if ERROR_FLAG in self.request.GET.keys(): return SimpleTemplateResponse('xadmin/views/invalid_setup.html', { 'title': _('Database error'), }) return HttpResponseRedirect(self.request.path + '?' + ERROR_FLAG + '=1') self.has_more = self.result_count > ( self.list_per_page * self.page_num + len(self.result_list))
def make_result_list(self): # Get search parameters from the query string. self.base_queryset = self.queryset() self.list_queryset = self.get_list_queryset() self.ordering_field_columns = self.get_ordering_field_columns() self.paginator = self.get_paginator() # Get the number of objects, with admin filters applied. self.result_count = self.paginator.count self.can_show_all = self.result_count <= self.list_max_show_all self.multi_page = self.result_count > self.list_per_page # Get the list of objects to display on this page. if (self.show_all and self.can_show_all) or not self.multi_page: self.result_list = self.list_queryset._clone() else: try: self.result_list = self.paginator.page( self.page_num + 1).object_list except InvalidPage: if ERROR_FLAG in self.request.GET.keys(): return SimpleTemplateResponse('xadmin/views/invalid_setup.html', { 'title': _('Database error'), }) return HttpResponseRedirect(self.request.path + '?' + ERROR_FLAG + '=1') self.has_more = self.result_count > ( self.list_per_page * self.page_num + len(self.result_list))
def paginate_queryset(self, queryset, request, view=None): """ Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view. """ page_size = self.get_page_size(request) if not page_size: return None paginator = self.django_paginator_class(queryset, page_size) page_number = request.query_params.get(self.page_query_param, 1) if page_number in self.last_page_strings: page_number = paginator.num_pages try: self.page = paginator.page(page_number) except InvalidPage as exc: msg = self.invalid_page_message.format( page_number=page_number, message=six.text_type(exc) ) raise NotFound(msg) if paginator.num_pages > 1 and self.template is not None: # The browsable API should display pagination controls. self.display_page_controls = True self.request = request return list(self.page)
def paginate_queryset(self, queryset, page_size): """ Paginate the queryset, if needed. This is EXACTLY the same as the standard ListView.paginate_queryset() except for this line: page = paginator.page(page_number, softlimit=True) Because we want to use the DiggPaginator's softlimit option. So that if you're viewing a page of, say, Flickr photos, and you switch from viewing by Uploaded Time to viewing by Taken Time, the new ordering might have fewer pages. In that case we want to see the final page, not a 404. The softlimit does that, but I can't see how to use it without copying all of this... """ paginator = self.get_paginator( queryset, page_size, orphans = self.get_paginate_orphans(), allow_empty_first_page = self.get_allow_empty(), body = self.paginator_body, margin = self.paginator_margin, padding = self.paginator_padding, tail = self.paginator_tail, ) page_kwarg = self.page_kwarg page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 try: page_number = int(page) except ValueError: if page == 'last': page_number = paginator.num_pages else: raise Http404(_("Page is not 'last', nor can it be converted to an int.")) try: page = paginator.page(page_number, softlimit=False) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage as e: raise Http404(_('Invalid page (%(page_number)s): %(message)s') % { 'page_number': page_number, 'message': str(e) })
def search(request): query = request.GET.get('q','') page_size = 20 after_range_num = 5 before_range_num = 4 if query: qset = ( Q(name__icontains=query) | Q(city__icontains=query) | Q(time__icontains=query) | Q(mile__icontains=query) | Q(price__icontains=query) ) result = GuaziCar.objects.filter(qset).distinct() paginator = Paginator(result, page_size) try: page = int(request.GET.get('page', '1')) if page < 1: page = 1 except ValueError: page = 1 try: contacts = paginator.page(page) except (EmptyPage,InvalidPage,PageNotAnInteger): contacts = paginator.page(paginator.num_pages) if page >= after_range_num: page_range = list(paginator.page_range)[page-after_range_num:page+before_range_num] else: page_range = list(paginator.page_range)[0:int(page)+before_range_num] return render(request, 'search.html', {'result': contacts, 'query': query, 'page_range': page_range }) else: result = [] return render(request, 'search.html', {})
def meeting_list(request, meetings, title=None): if not title: title = _('Meetings') paginator = Paginator(meetings, 12) try: meetings = paginator.page(int(request.GET.get('page', '1'))) except (EmptyPage, InvalidPage): meetings = paginator.page(1) return render(request, 'meetings/list.html', { 'meetings': meetings, 'title': title, })
def invoice_list(request): invoices = Invoice.objects.all().order_by('-created_at') paginator = Paginator(invoices, 25) try: invoices = paginator.page(int(request.GET.get('page', '1'))) except (EmptyPage, InvalidPage): invoices = paginator.page(1) return render(request, 'billing/invoice_list.html', { 'invoices': invoices, })
def checklist_payment_list(request): payments = ChecklistPayment.objects.all().order_by('-created_at') paginator = Paginator(payments, 25) try: payments = paginator.page(int(request.GET.get('page', '1'))) except (EmptyPage, InvalidPage): payments = paginator.page(1) return render(request, 'billing/checklist_payment_list.html', { 'payments': payments, })