[Django]-How to route to specific viewset methods Django

2👍

You didn’t convert your router into a urlpatterns list, so you won’t be able to access your viewset regardless.

To convert the router:

from rest_framework.routers import DefaultRouter
from users.views import (UserViewSet, testing)

router = DefaultRouter()    
router.register(r"users", UserViewSet, basename="users")
    
urlpatterns = [
    path('testing', testing),
    *router.urls,
]

In Django Rest Framework, a viewset’s create method is executed during a POST request to a particular uri. In your case, this uri would be /users.

If you would like to add an additional method that triggers at /users/create, you will need to use the action decorator:

from rest_framework import viewsets
from rest_framework.response import JsonResponse

class UserViewSet(viewsets.ViewSet):
    @action(methods=['GET'], url_path='create')
    def my_custom_action(self):
        return JsonResponse({
            'the create endpoint'
        })

Since create is a reserved method on DRF viewsets, you will need to name the method something else (in the example, my_custom_action), and set the url_path parameter accordingly.

If you were to omit the url_path, the path would default to the name of the method, eg. /users/my_custom_action.

Leave a comment