Skip to content

Commit 4bcbf69

Browse files
Document ViewSet.action (#5685)
Closes #2941 Provides example of adjusting permission by action.
1 parent e87fcbb commit 4bcbf69

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

docs/api-guide/viewsets.md

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,10 @@ There are two main advantages of using a `ViewSet` class over using a `View` cla
7070

7171
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.
7272

73-
## Marking extra actions for routing
7473

75-
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below:
74+
## ViewSet actions
75+
76+
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below:
7677

7778
class UserViewSet(viewsets.ViewSet):
7879
"""
@@ -101,6 +102,23 @@ The default routers included with REST framework will provide routes for a stand
101102
def destroy(self, request, pk=None):
102103
pass
103104

105+
During dispatch the name of the current action is available via the `.action` attribute.
106+
You may inspect `.action` to adjust behaviour based on the current action.
107+
108+
For example, you could restrict permissions to everything except the `list` action similar to this:
109+
110+
def get_permissions(self):
111+
"""
112+
Instantiates and returns the list of permissions that this view requires.
113+
"""
114+
if self.action == 'list':
115+
permission_classes = [IsAuthenticated]
116+
else:
117+
permission_classes = [IsAdmin]
118+
return [permission() for permission in permission_classes]
119+
120+
## Marking extra actions for routing
121+
104122
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.
105123

106124
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.

0 commit comments

Comments
 (0)