Adding additional actions to ViewSets
You can add extra actions to ViewSets
. Let’s change the CourseEnrollView
view into a custom ViewSet
action. Edit the api/views.py
file and modify the CourseViewSet
class to look as follows:
# ...
from rest_framework.decorators import action
class CourseViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Course.objects.prefetch_related('modules')
serializer_class = CourseSerializer
@action(
detail=True,
methods=['post'],
authentication_classes=[BasicAuthentication],
permission_classes=[IsAuthenticated]
)
def enroll(self, request, *args, **kwargs):
course = self.get_object()
course.students.add(request.user)
return Response({'enrolled': True})
In the preceding code, you add a custom enroll()
method that represents an additional action for this ViewSet
. The preceding code is as follows:
- You use the
action
decorator of...