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
""" ViewSets are essentially just a type of class based view, that doesn't provide any method handlers, such as `get()`, `post()`, etc... but instead has actions, such as `list()`, `retrieve()`, `create()`, etc...
Actions are only bound to methods at the point of instantiating the views.
user_list = UserViewSet.as_view({'get': 'list'}) user_detail = UserViewSet.as_view({'get': 'retrieve'})
Typically, rather than instantiate views from viewsets directly, you'll regsiter the viewset with a router and let the URL conf be determined automatically.
router = DefaultRouter() router.register(r'users', UserViewSet, 'user') urlpatterns = router.urls """
""" This is the magic.
Overrides `.as_view()` so that it takes an `actions` keyword that performs the binding of HTTP methods to actions on the Resource.
For example, to create a concrete view binding the 'GET' and 'POST' methods to the 'list' and 'create' actions...
view = MyViewSet.as_view({'get': 'list', 'post': 'create'}) """
""" Because of the way class based views create a closure around the instantiated view, we need to totally reimplement `.as_view`, and slightly modify the view function that is created and returned. """ # The suffix initkwarg is reserved for identifing the viewset type # eg. 'List' or 'Instance'.
# sanitize keyword arguments raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don't do that." % (key, cls.__name__)) raise TypeError("%s() received an invalid keyword %r" % ( cls.__name__, key))
# We also store the mapping of request methods to actions, # so that we can later set the action attribute. # eg. `self.action = 'list'` on an incoming GET request.
# Bind methods to actions # This is the bit that's different to a standard view
# Patch this in as it's otherwise only present from 1.5 onwards
# And continue as usual
# take name and docstring from class
# and possible attributes set by decorators # like csrf_exempt from dispatch
# We need to set these on the view function, so that breadcrumb # generation can pick out these bits of information from a # resolved URL.
""" Set the `.action` attribute on the view, depending on the request method. """
""" The base ViewSet class does not provide any actions by default. """
""" The GenericViewSet class does not provide any actions by default, but does include the base set of generic view behavior, such as the `get_object` and `get_queryset` methods. """
mixins.ListModelMixin, GenericViewSet): """ A viewset that provides default `list()` and `retrieve()` actions. """
mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet): """ A viewset that provides default `create()`, `retrieve()`, `update()`, `partial_update()`, `destroy()` and `list()` actions. """ |