Member-only story
Routing for Extra Actions in Django REST Framework ViewSets
In Django REST Framework (DRF), ViewSet classes provide a convenient way to bundle related endpoints into a single class.
While standard actions like list, create, retrieve, update, and destroy cover most use cases, you’ll often need to add custom functionality that doesn’t fit neatly into these predefined actions.
This is where extra actions come into play.
Defining Extra Actions with @action
DRF allows you to define custom actions within your ViewSet using the @action decorator.
These extra actions are automatically included in the generated routes, so they behave like standard endpoints but with custom logic tailored to your application.
Example
Here’s how you could add a set_password action to a UserViewSet:
from myapp.permissions import IsAdminOrIsSelf
from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet
class UserViewSet(ModelViewSet):
...
@action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])
def set_password(self, request, pk=None):
# Custom logic for setting a user password
...This would generate:
- URL pattern:
^users/{pk}/change-password/$ - URL name:
user-change_password