Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
""" Generic views that provide commonly needed behaviour. """
""" Same as Django's standard shortcut, but make sure to raise 404 if the filter_kwargs don't match the required types. """
""" Base class for all other generic views. """
# You'll need to either set these attributes, # or override `get_queryset()`/`get_serializer_class()`.
# This shortcut may be used instead of setting either or both # of the `queryset`/`serializer_class` attributes, although using # the explicit style is generally preferred.
# If you want to use object lookups other than pk, set this attribute. # For more complex lookup requirements override `get_object()`.
# Pagination settings
# The filter backend classes to use for queryset filtering
# The following attributes may be subject to change, # and should be considered private API.
###################################### # These are pending deprecation...
""" Extra context provided to the serializer class. """ 'request': self.request, 'format': self.format_kwarg, 'view': self }
files=None, many=False, partial=False): """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """ many=many, partial=partial, context=context)
""" Return a serializer instance to use with paginated data. """
""" Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view. """ warnings.warn('The `page_size` parameter to `paginate_queryset()` ' 'is due to be deprecated. ' 'Note that the return style of this method is also ' 'changed, and will simply return a page object ' 'when called without a `page_size` argument.', PendingDeprecationWarning, stacklevel=2) deprecated_style = True else: # Determine the required page size. # If pagination is not configured, simply return None.
warnings.warn( 'The `allow_empty` parameter is due to be deprecated. ' 'To use `allow_empty=False` style behavior, You should override ' '`get_queryset()` and explicitly raise a 404 on empty querysets.', PendingDeprecationWarning, stacklevel=2 )
allow_empty_first_page=self.allow_empty) 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.")) except InvalidPage as e: raise Http404(_('Invalid page (%(page_number)s): %(message)s') % { 'page_number': page_number, 'message': str(e) })
return (paginator, page, page.object_list, page.has_other_pages())
""" Given a queryset, filter it with whichever filter backend is in use.
You are unlikely to want to override this method, although you may need to call it either from a list view, or from a custom `get_object` method if you want to apply the configured filtering backend to the default queryset. """ warnings.warn( 'The `filter_backend` attribute and `FILTER_BACKEND` setting ' 'are due to be deprecated in favor of a `filter_backends` ' 'attribute and `DEFAULT_FILTER_BACKENDS` setting, that take ' 'a *list* of filter backend classes.', PendingDeprecationWarning, stacklevel=2 ) filter_backends = [self.filter_backend]
######################## ### The following methods provide default implementations ### that you may want to override for more complex cases.
""" Return the size of pages to use with pagination.
If `PAGINATE_BY_PARAM` is set it will attempt to get the page size from a named query parameter in the url, eg. ?page_size=100
Otherwise defaults to using `self.paginate_by`. """ warnings.warn('The `queryset` parameter to `get_paginate_by()` ' 'is due to be deprecated.', PendingDeprecationWarning, stacklevel=2)
""" Return the class to use for the serializer. Defaults to using `self.serializer_class`.
You may want to override this if you need to provide different serializations depending on the incoming request.
(Eg. admins get full serialization, others get basic serialization) """
"'%s' should either include a 'serializer_class' attribute, " \ "or use the 'model' attribute as a shortcut for " \ "automatically generating a serializer class." \ % self.__class__.__name__
""" Get the list of items for this view. This must be an iterable, and may be a queryset. Defaults to using `self.queryset`.
You may want to override this if you need to provide different querysets depending on the incoming request.
(Eg. return a list of items that is specific to the user) """
raise ImproperlyConfigured("'%s' must define 'queryset' or 'model'" % self.__class__.__name__)
""" Returns the object the view is displaying.
You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. """ # Determine the base queryset to use. else: pass # Deprecation warning
# Perform the lookup filtering.
elif pk is not None and self.lookup_field == 'pk': warnings.warn( 'The `pk_url_kwarg` attribute is due to be deprecated. ' 'Use the `lookup_field` attribute instead', PendingDeprecationWarning ) filter_kwargs = {'pk': pk} elif slug is not None and self.lookup_field == 'pk': warnings.warn( 'The `slug_url_kwarg` attribute is due to be deprecated. ' 'Use the `lookup_field` attribute instead', PendingDeprecationWarning ) filter_kwargs = {self.slug_field: slug} else: raise ImproperlyConfigured( 'Expected view %s to be called with a URL keyword argument ' 'named "%s". Fix your URL conf, or set the `.lookup_field` ' 'attribute on the view correctly.' % (self.__class__.__name__, self.lookup_field) )
# May raise a permission denied
######################## ### The following are placeholder methods, ### and are intended to be overridden. ### ### The are not called by GenericAPIView directly, ### but are used by the mixin methods.
""" Placeholder method for calling before saving an object.
May be used to set attributes on the object that are implicit in either the request, or the url. """
""" Placeholder method for calling after saving an object. """
""" Return a dictionary of metadata about the view. Used to return responses for OPTIONS requests.
We override the default behavior, and add some extra information about the required request body for POST and PUT operations. """
# Test global permissions # Test object permissions else: # If user has appropriate permissions for the view, include # appropriate metadata about the fields that should be supplied.
########################################################## ### Concrete view classes that provide method handlers ### ### by composing the mixin classes with the base view. ### ##########################################################
GenericAPIView):
""" Concrete view for creating a model instance. """ return self.create(request, *args, **kwargs)
GenericAPIView): """ Concrete view for listing a queryset. """
GenericAPIView): """ Concrete view for retrieving a model instance. """
GenericAPIView):
""" Concrete view for deleting a model instance. """ return self.destroy(request, *args, **kwargs)
GenericAPIView):
""" Concrete view for updating a model instance. """ return self.update(request, *args, **kwargs)
return self.partial_update(request, *args, **kwargs)
mixins.CreateModelMixin, GenericAPIView): """ Concrete view for listing a queryset or creating a model instance. """
mixins.UpdateModelMixin, GenericAPIView): """ Concrete view for retrieving, updating a model instance. """ return self.retrieve(request, *args, **kwargs)
return self.update(request, *args, **kwargs)
return self.partial_update(request, *args, **kwargs)
mixins.DestroyModelMixin, GenericAPIView): """ Concrete view for retrieving or deleting a model instance. """ return self.retrieve(request, *args, **kwargs)
return self.destroy(request, *args, **kwargs)
mixins.UpdateModelMixin, mixins.DestroyModelMixin, GenericAPIView): """ Concrete view for retrieving, updating or deleting a model instance. """
########################## ### Deprecated classes ### ##########################
warnings.warn( 'Subclassing `MultipleObjectAPIView` is due to be deprecated. ' 'You should simply subclass `GenericAPIView` instead.', PendingDeprecationWarning, stacklevel=2 ) super(MultipleObjectAPIView, self).__init__(*args, **kwargs)
warnings.warn( 'Subclassing `SingleObjectAPIView` is due to be deprecated. ' 'You should simply subclass `GenericAPIView` instead.', PendingDeprecationWarning, stacklevel=2 ) super(SingleObjectAPIView, self).__init__(*args, **kwargs) |