From 4bcbf691cf312a4e41b8c20568cbf6e8cff4bd00 Mon Sep 17 00:00:00 2001 From: Carlton Gibson Date: Tue, 19 Dec 2017 12:06:57 +0100 Subject: [PATCH] Document ViewSet.action (#5685) Closes #2941 Provides example of adjusting permission by action. --- docs/api-guide/viewsets.md | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 04ce7357d..27fb1d780 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -70,9 +70,10 @@ There are two main advantages of using a `ViewSet` class over using a `View` cla Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout. -## Marking extra actions for routing -The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below: +## ViewSet actions + +The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below: class UserViewSet(viewsets.ViewSet): """ @@ -101,6 +102,23 @@ The default routers included with REST framework will provide routes for a stand def destroy(self, request, pk=None): pass +During dispatch the name of the current action is available via the `.action` attribute. +You may inspect `.action` to adjust behaviour based on the current action. + +For example, you could restrict permissions to everything except the `list` action similar to this: + + def get_permissions(self): + """ + Instantiates and returns the list of permissions that this view requires. + """ + if self.action == 'list': + permission_classes = [IsAuthenticated] + else: + permission_classes = [IsAdmin] + return [permission() for permission in permission_classes] + +## Marking extra actions for routing + If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@detail_route` or `@list_route` decorators. The `@detail_route` decorator contains `pk` in its URL pattern and is intended for methods which require a single instance. The `@list_route` decorator is intended for methods which operate on a list of objects.