User Authentication in Django REST Framework

前端 未结 3 482
长发绾君心
长发绾君心 2021-01-26 02:55

I have a Django REST backend, and it has a /users endpoint where I can add new users through POST method from frontend.

/users end

3条回答
  •  天命终不由人
    2021-01-26 03:31

    Finally, I find a method to solve this problem.

    Here has a very elegant way to do this, rewrite get_queryset function in my UserViewSet:

    class UserViewSet(viewsets.ModelViewSet):
    
        # permission_classes = (permissions.IsAdminUser, )
        permission_classes = (permissions.AllowAny, )  # <-- change 1
        # queryset = User.objects.all()  # <-- change 2
        serializer_class = UserSerializer
    
        def get_queryset(self):
            queryset = User.objects.filter(id=self.request.user.id)
            if self.request.user.is_superuser:
                queryset = User.objects.all()
            return queryset
    

    In change 1, permissions allowed anyone to access, so a new user can do a POST without any authentication.

    In change 2, I only return all users when the user is superuser, just like rewrote get_queryset done.

    Also need to change urls.py file to add base_name for this url like this:

    router.register(r'users', UserViewSet, base_name='user')
    

    ref, https://stackoverflow.com/a/22767325/2803344

提交回复
热议问题