43 lines
1.5 KiB
Python
43 lines
1.5 KiB
Python
|
|
from rest_framework import viewsets, permissions, status
|
||
|
|
from rest_framework.response import Response
|
||
|
|
from rest_framework.views import APIView
|
||
|
|
from rest_framework.decorators import action
|
||
|
|
from django.contrib.auth import get_user_model
|
||
|
|
from .models import User
|
||
|
|
from .serializers import UserSerializer, UserRegistrationSerializer
|
||
|
|
|
||
|
|
User = get_user_model()
|
||
|
|
|
||
|
|
|
||
|
|
class UserViewSet(viewsets.ModelViewSet):
|
||
|
|
queryset = User.objects.all()
|
||
|
|
serializer_class = UserSerializer
|
||
|
|
permission_classes = [permissions.AllowAny]
|
||
|
|
|
||
|
|
def get_queryset(self):
|
||
|
|
if self.action == 'retrieve':
|
||
|
|
return User.objects.all()
|
||
|
|
return User.objects.none()
|
||
|
|
|
||
|
|
@action(detail=False, methods=['get'])
|
||
|
|
def me(self, request):
|
||
|
|
if request.user.is_authenticated:
|
||
|
|
serializer = self.get_serializer(request.user)
|
||
|
|
return Response(serializer.data)
|
||
|
|
return Response({'detail': 'Not authenticated'}, status=status.HTTP_401_UNAUTHORIZED)
|
||
|
|
|
||
|
|
|
||
|
|
class UserRegistrationView(APIView):
|
||
|
|
permission_classes = [permissions.AllowAny]
|
||
|
|
|
||
|
|
def post(self, request):
|
||
|
|
serializer = UserRegistrationSerializer(data=request.data)
|
||
|
|
if serializer.is_valid():
|
||
|
|
user = serializer.save()
|
||
|
|
return Response({
|
||
|
|
'id': user.id,
|
||
|
|
'username': user.username,
|
||
|
|
'message': '用户创建成功'
|
||
|
|
}, status=status.HTTP_201_CREATED)
|
||
|
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|