Помогите понять, почему не существует эндпоинта api/users/register
, но существуют api/users/{pk}/register
?
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)),
]