Getting error "'list' object is not callable" for authentication_classes

202 Views Asked by At

I have following method:

class AbcViewSet(viwesets.ModelViewSet):

    @action(detail=False, permission_classes=(IsOwnerOrReadOnly,))
    @debugger_queries
    def get_xyz(self, request, pk=None):
        # ...

Inside this method, request.user was always AnonymousUser. I felt that it was because I did not specify any kind of authentication for this method. I skipped through codebase and found other developers using decorator. So, I tried by adding a decorator @authentication_classes([TokenAuthentication,]) as follows:

class AbcViewSet(viwesets.ModelViewSet):

    @action(detail=False, permission_classes=(IsOwnerOrReadOnly,))
    @debugger_queries
    @authentication_classes([TokenAuthentication,])
    def get_xyz(self, request, pk=None):
        # ...

But it started me giving 'list' object is not callable error on this newly added line. I was expecting it to work as we can see similar code here: 1, 2. Django doc too state it here.

Is it that they are used with function based views and are not allowed with View sets? What I am missing here?

PS:

My settings.py does have TokenAuthentication specified:

REST_FRAMEWORK = {

    # ...

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ),

    # ...
}

PS2: I also tried following, though its somewhat unrelated to the error:

@authentication_classes((TokenAuthentication))

and

@authentication_classes((TokenAuthentication,))
1

There are 1 best solutions below

0
On

The doc says:

You can also set the authentication scheme on a per-view or per-viewset basis, using the APIView class-based views.

 authentication_classes = [SessionAuthentication, BasicAuthentication]

So I added it as class variable:

class AbcViewSet(viwesets.ModelViewSet):

    authentication_classes = [TokenAuthentication, SessionAuthentication]  # <<=====

    @action(detail=False, permission_classes=(IsOwnerOrReadOnly,))
    @debugger_queries
    def get_xyz(self, request, pk=None):
        # ...

And the error is gone.

It was my lack of knowledge that I should not be using @authentication_classes decorator in view set, instead define the authentication_classes variable in the class.