Django REST Framework - Define extra arguments using the @action decorator

The problem with my solution is that on the auto-generated doc page I'm seeing the form with the UserSerializer fields.

From the documentation:

The decorator can additionally take extra arguments that will be set for the routed view only. For example:

That means that anything that can be used as a class property can also be used as an argument for @action(), including serializer_class:

@action(methods=['post'], detail=True, serializer_class=FollowSerializer)
def follow(self, request, pk=None):
    # ...
    serializer = self.get_serializer(data=request.data)
    # ...

This will result in the correct form appearing in the auto-generated docs.


You could pass target_id through url as,api/users/{id}/follow/{target_id} , but you have to change the views as,

class UserViewSet(viewsets.ModelViewSet):
    """
    A viewset that provides the standard actions
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

    @action(methods=['post'], detail=True)
    def follow(self, request, *args, **kwargs):
        user = self.get_object()
        target_user = int(kwargs['target_id'])
        Follow.objects.create(user=user, target=target_user)
        return Response(status=status.HTTP_204_NO_CONTENT)

and define a seperate path() in urls.py as,

urlpatterns = [
                  path('users/<int:pk>/follow/<int:target_id>/', UserViewSet.as_view({"post": "follow"}))

              ]