|
|
|
from django.contrib.auth.models import User
|
|
|
|
from rest_framework import viewsets
|
|
|
|
from rest_framework.permissions import AllowAny, IsAuthenticatedOrReadOnly
|
|
|
|
|
|
|
|
from user_info.serializers import UserRegisterSerializer
|
|
|
|
from user_info.permissions import IsSelfOrReadOnly
|
|
|
|
|
|
|
|
from rest_framework.decorators import action
|
|
|
|
from rest_framework.response import Response
|
|
|
|
from user_info.serializers import UserDetailSerializer
|
|
|
|
|
|
|
|
|
|
|
|
class UserViewSet(viewsets.ModelViewSet):
|
|
|
|
queryset = User.objects.all()
|
|
|
|
serializer_class = UserRegisterSerializer
|
|
|
|
lookup_field = 'username' # 和UserRegisterSerializer中的url中lookup_field对应
|
|
|
|
|
|
|
|
# http://127.0.0.1:8000/api/user/admin/info/
|
|
|
|
@action(detail=True, methods=['get'])
|
|
|
|
def info(self, request, username=None):
|
|
|
|
queryset = User.objects.get(username=username)
|
|
|
|
serializer = UserDetailSerializer(queryset, many=False)
|
|
|
|
return Response(serializer.data)
|
|
|
|
|
|
|
|
# http://127.0.0.1:8000/api/user/sorted/
|
|
|
|
@action(detail=False)
|
|
|
|
def sorted(self, request):
|
|
|
|
users = User.objects.all().order_by('-username')
|
|
|
|
# 是否分页
|
|
|
|
page = self.paginate_queryset(users)
|
|
|
|
if page is not None:
|
|
|
|
serializer = self.get_serializer(page, many=True)
|
|
|
|
return self.get_paginated_response(serializer.data)
|
|
|
|
serializer = self.get_serializer(users, many=True)
|
|
|
|
return Response(serializer.data)
|
|
|
|
|
|
|
|
def get_permissions(self):
|
|
|
|
# 注册用户的POST请求是允许所有人都可以操作的
|
|
|
|
if self.request.method == 'POST':
|
|
|
|
self.permission_classes = [AllowAny]
|
|
|
|
else:
|
|
|
|
self.permission_classes = [IsAuthenticatedOrReadOnly, IsSelfOrReadOnly]
|
|
|
|
|
|
|
|
return super(UserViewSet, self).get_permissions()
|