我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用django.core.paginator.Page()。
def data(self): """ Returns the serialized data on the serializer. """ if self._data is None: obj = self.object if self.many is not None: many = self.many else: many = hasattr(obj, '__iter__') and not isinstance(obj, (Page, dict)) if many: raise AssertionError('Implicit list/queryset serialization is deprecated. ' 'Use the `many=True` flag when instantiating the serializer.') if many: self._data = [self.to_native(item) for item in obj] else: self._data = self.to_native(obj) return self._data # noinspection PyMethodMayBeStatic
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 page(self, number): """ Returns 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 page_items = self.object_list[bottom:top] # check moved from validate_number if not page_items: if number == 1 and self.allow_empty_first_page: pass else: raise EmptyPage('That page contains no results') return InfinitePage(page_items, number, self)
def __repr__(self): return '<Page %s>' % self.number
def page(self, number): """ Returns a Page object for the given 1-based page number. """ number = self.validate_number(number) # remove the extra item(s) when creating the page page_items = self.object_list[:self.per_page] return FinitePage(page_items, number, self)
def __init__(self, object_list, number, paginator, facets): self.facets = facets super(Page, self).__init__(object_list, number, paginator)
def page(self, number): """Returns a Page object for the given 1-based page number. :param number: :return: """ 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 object_list = self.object_list[bottom:top].execute() __facets = getattr(object_list, 'aggregations', None) return self._get_page(object_list, number, self, facets=__facets)
def _get_page(self, *args, **kwargs): """Get page. Returns 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)
def current_page(self): try: page = int(self.request.GET['page']) if page <= 0: raise ValueError() except (ValueError, KeyError): page = self.default try: return self.page(page) except EmptyPage: return Page([], page, self)
def _data_convert(data, time_func, foreign, many, include_attr, exclude_attr): if isinstance(data, models.Model): attr_list = _get_attr(data, time_func, foreign, many) _include_check(include_attr, attr_list) _exclude_check(exclude_attr, attr_list) return attr_list elif isinstance(data, (QuerySet, Page)): result = [] for itm in data: attr_list = _get_attr(itm, time_func, foreign, many) _include_check(include_attr, attr_list) _exclude_check(exclude_attr, attr_list) result.append(copy.copy(attr_list)) return result elif isinstance(data, datetime.datetime): print ('====') print (str(data)) return time_func(data) elif isinstance(data, (str, bool, float)): return data elif isinstance(data, dict): for k, v in data.iteritems(): data[k] = _data_convert(v, time_func, foreign, many, include_attr, exclude_attr) return data elif isinstance(data, list): for i, itm in enumerate(data): data[i] = _data_convert(itm, time_func, foreign, many, include_attr, exclude_attr) return data else: return None
def page(self, 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 Page(self.object_list.get_slice(bottom,self.per_page), number, self)
def _get_page(self, object_list, number, paginator): object_list = map(self._map_function, object_list) return Page(object_list, number, paginator)
def page(self, number): """ Returns 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 return self._get_page(self.object_list[bottom:top], number, self)
def _get_page(self, *args, **kwargs): """ Returns an instance of a single page. This hook can be used by subclasses to use an alternative to the standard :cls:`Page` object. """ return EndlessPage(*args, **kwargs)
def __repr__(self): return '<Page %s of Endless Page>' % self.number
def get_raw_data_form(self, data, view, method, request): """ Returns a form that allows for arbitrary content types to be tunneled via standard HTML forms. (Which are typically application/x-www-form-urlencoded) """ # See issue #2089 for refactoring this. serializer = getattr(data, 'serializer', None) if serializer and not getattr(serializer, 'many', False): instance = getattr(serializer, 'instance', None) if isinstance(instance, Page): instance = None else: instance = None with override_method(view, request, method) as request: # Check permissions if not self.show_form_for_method(view, method, request, instance): return # If possible, serialize the initial content for the generic form default_parser = view.parser_classes[0] renderer_class = getattr(default_parser, 'renderer_class', None) if hasattr(view, 'get_serializer') and renderer_class: # View has a serializer defined and parser class has a # corresponding renderer that can be used to render the data. if method in ('PUT', 'PATCH'): serializer = view.get_serializer(instance=instance) else: serializer = view.get_serializer() # Render the raw data content renderer = renderer_class() accepted = self.accepted_media_type context = self.renderer_context.copy() context['indent'] = 4 content = renderer.render(serializer.data, accepted, context) else: content = None # Generate a generic form that includes a content type field, # and a content field. media_types = [parser.media_type for parser in view.parser_classes] choices = [(media_type, media_type) for media_type in media_types] initial = media_types[0] class GenericContentForm(forms.Form): _content_type = forms.ChoiceField( label='Media type', choices=choices, initial=initial, widget=forms.Select(attrs={'data-override': 'content-type'}) ) _content = forms.CharField( label='Content', widget=forms.Textarea(attrs={'data-override': 'content'}), initial=content ) return GenericContentForm()
def get_raw_data_form(self, data, view, method, request): """ Returns a form that allows for arbitrary content types to be tunneled via standard HTML forms. (Which are typically application/x-www-form-urlencoded) """ # See issue #2089 for refactoring this. serializer = getattr(data, 'serializer', None) if serializer and not getattr(serializer, 'many', False): instance = getattr(serializer, 'instance', None) if isinstance(instance, Page): instance = None else: instance = None with override_method(view, request, method) as request: # Check permissions if not self.show_form_for_method(view, method, request, instance): return # If possible, serialize the initial content for the generic form default_parser = view.parser_classes[0] renderer_class = getattr(default_parser, 'renderer_class', None) if (hasattr(view, 'get_serializer') and renderer_class): # View has a serializer defined and parser class has a # corresponding renderer that can be used to render the data. if method in ('PUT', 'PATCH'): serializer = view.get_serializer(instance=instance) else: serializer = view.get_serializer() # Render the raw data content renderer = renderer_class() accepted = self.accepted_media_type context = self.renderer_context.copy() context['indent'] = 4 content = renderer.render(serializer.data, accepted, context) else: content = None # Generate a generic form that includes a content type field, # and a content field. media_types = [parser.media_type for parser in view.parser_classes] choices = [(media_type, media_type) for media_type in media_types] initial = media_types[0] class GenericContentForm(forms.Form): _content_type = forms.ChoiceField( label='Media type', choices=choices, initial=initial, widget=forms.Select(attrs={'data-override': 'content-type'}) ) _content = forms.CharField( label='Content', widget=forms.Textarea(attrs={'data-override': 'content'}), initial=content ) return GenericContentForm()
def errors(self): """ Run deserialization and return error data, setting self.object if no errors occurred. """ if self._errors is None: data, files = self.init_data, self.init_files if self.many is not None: many = self.many else: many = hasattr(data, '__iter__') and not isinstance(data, (Page, dict, six.text_type)) if many: raise AssertionError('Implicit list/queryset serialization is deprecated. ' 'Use the `many=True` flag when instantiating the serializer.') if many: ret = RelationsList() errors = [] update = self.object is not None if update: # If this is a bulk update we need to map all the objects # to a canonical identity so we can determine which # individual object is being updated for each item in the # incoming data objects = self.object identities = [self.get_identity(self.to_native(obj)) for obj in objects] identity_to_objects = dict(zip(identities, objects)) if hasattr(data, '__iter__') and not isinstance(data, (dict, six.text_type)): for item in data: if update: # Determine which object we're updating identity = self.get_identity(item) # noinspection PyUnboundLocalVariable self.object = identity_to_objects.pop(identity, None) if self.object is None and not self.allow_add_remove: ret.append(None) errors.append({'non_field_errors': [ 'Cannot create a new item, only existing items may be updated.' ]}) continue ret.append(self.from_native(item, None)) errors.append(self._errors) if update and self.allow_add_remove: ret._deleted = identity_to_objects.values() self._errors = any(errors) and errors or [] else: self._errors = {'non_field_errors': ['Expected a list of items.']} else: ret = self.from_native(data, files) if not self._errors: self.object = ret return self._errors