Skip to content

Improve documentation regarding serializer class on extra actions. #6410

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/api-guide/viewsets.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ A more complete example of extra actions:
queryset = User.objects.all()
serializer_class = UserSerializer

@action(detail=True, methods=['post'])
@action(detail=True, methods=['post'], serializer_class=PasswordSerializer)
Copy link
Collaborator

@carltongibson carltongibson Jan 22, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we then use self.get_serializer() in the method body? (Otherwise the kwarg isn’t doing anything...)

(Although see main comment.)

def set_password(self, request, pk=None):
user = self.get_object()
serializer = PasswordSerializer(data=request.data)
Expand All @@ -168,9 +168,9 @@ A more complete example of extra actions:
serializer = self.get_serializer(recent_users, many=True)
return Response(serializer.data)

The decorator can additionally take extra arguments that will be set for the routed view only. For example:
The decorator can additionally take extra arguments that will be set for the routed view only. Any class property of the `ViewSet` is therefore a valid argument for `@action()` (e.g. `serializer_class`, `queryset`, `permission_classes`). For example, an action which sets a password needs different permissions and a different form to be displayed compared to the regular `UserViewSet`:

@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf])
@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf], serializer_class=PasswordSerializer)
def set_password(self, request, pk=None):
...

Expand Down