Django-rest-framework permissions for create in viewset

前端 未结 3 1405
我寻月下人不归
我寻月下人不归 2020-12-28 08:18

I am trying to create a REST API and am stuck at user registration: basically I need to have the access token before I register.

This is the view:

cl         


        
3条回答
  •  失恋的感觉
    2020-12-28 09:20

    You could utilizing Django REST Framework's ability to define custom permissions. You can specify both a has_permission and has_object_permission within a custom class. This will give you the expected behavior of throwing 403s to anon users for everything except posting to the creation endpoint. It might look something like:

    class IsAnonCreate(permissions.BasePermission):
        def has_permission(self, request, view):
            if request.method == "POST" and not request.user.is_authenticated():
                return True
            elif not request.user.is_authenticated() and request.method != "POST":
                return False
            elif request.method in permissions.SAFE_METHODS:
                return True
    
            return False
    
        def has_object_permission(self, request, view, obj):
            if not request.user.is_authenticated():
                return False
            if request.method in permissions.SAFE_METHODS:
                return True
    
            return obj.username == request.user.username
    

    You could then add some custom handling for authenticated users if you wanted.

    Then all you need to do is add the permission class to your ModelViewSet:

    class UserViewSet(viewsets.ModelViewSet):
    
        """
        API endpoint that allows users to be viewed or edited.
        """
        queryset = User.objects.all()
        serializer_class = UserSerializer
        permission_classes = (IsAnonCreate, )
    

提交回复
热议问题