Adding additional actions to view sets

You can add extra actions to view sets. Let's change our previous CourseEnrollView view into a custom view set action. Edit the api/views.py file and modify the CourseViewSet class to look as follows:

from rest_framework.decorators import detail_routeclass CourseViewSet(viewsets.ReadOnlyModelViewSet):    queryset = Course.objects.all()    serializer_class = CourseSerializer    @detail_route(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})

We add a custom enroll() method that represents an additional action for this view ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.