Using different authentication for different operations in ModelViewSet in Django REST structure

I have the following ModelViewSet

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

I want create method (POST on /users/)not to request any authentication. How can I override authentication_classes in this case? I am talking about ModelViewSetnot general representations of the API.

+4
source share
1 answer

I want the create (POST on / users /) method not to request any authentication.

Actually, this is not exactly what you want. You want POSTusers to not require any permissions, which can lead to the successful completion of authenticated or unauthorized requests.

, POST. .

- :

class IsAuthenticatedOrCreate(permissions.IsAuthenticated):
    def has_permission(self, request, view):
        if request.method == 'POST':
            return True
        return super(IsAuthenticatedOrCreate, self).has_permission(request, view)

, , - .

+6

Source: https://habr.com/ru/post/1530237/


All Articles