Help to understand why endpoint api/users/register does not exist, but api/users/{pk}/register exist?

views.py

 from rest_framework import viewsets from rest_framework.decorators import api_view, action from rest_framework.response import Response from rest_framework import status from django.contrib.auth.models import User from .serializers import UserSerializer class UserView(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() @action(methods=['POST'], detail=True) def register(self, request): serialized = UserSerializer(data=request.data) if serialized.is_valid(): user = User.objects.create_user( username=serialized.data['username'], password=serialized.data['password'], email=serialized.data['email'] ) user.save() return Response('user registered', status=status.HTTP_201_CREATED) return Response('invalid data', status=status.HTTP_400_BAD_REQUEST) 

serializers.py

 from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'password', 'id') 

urls.py

 from django.contrib import admin from django.urls import path, include from rest_framework import routers from api import views router = routers.DefaultRouter() router.register(r'users', views.UserView, 'users') urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), ] 

    1 answer 1

    The action dekedirovanie @action , depending on the value of the detail argument, can be intended both for an individual object and for the entire collection. In your case, you must use detail=False :

     @action(methods=['POST'], detail=False) def register(self, request): serialized = UserSerializer(data=request.data) if serialized.is_valid(): user = User.objects.create_user( username=serialized.data['username'], password=serialized.data['password'], email=serialized.data['email'] ) user.save() return Response('user registered', status=status.HTTP_201_CREATED) return Response('invalid data', status=status.HTTP_400_BAD_REQUEST) 
    • Tell me more, please, is it possible to somehow create @action with the same name, for use with both the object and the collection? - junkkerrigan 5:28 pm
    • one
      When declaring two methods with the same name inside the class body, the lower one by code will be used. Well, detail is a required argument for the action decorator, you have to use either True or False . - avtomato 7:31 pm