tolga
tolga

Reputation: 2800

request.user.id is null in ModelViewSet

When I try to get active user id with request.user.id, it is always null:

@action(methods=['get'], detail=False)
def instructor_detail(self, request):
    response_data = {}
    instructor = InstructorRepository.getInstructor(request.user.id)
    response_data["data"] = {"user_id": request.user.id, "detail": instructor.get("detail")}

When I test that method (getInstructor) with an id, it works. The problem is, request.user.id is always null, even there's no login problem related with JWT based auth.

What should I check?

Upvotes: 1

Views: 490

Answers (1)

tolga
tolga

Reputation: 2800

I found the answer. My method was under InstructorView, which doesn't force any permission classes.

I guess views without any permission class doesn't provide a request.user data, is this true?

class InstructorView(viewsets.ModelViewSet):  
    permission_classes = ()
    authentication_classes = ()

So I relocated the method under another view with permission class:

class InstructorAdminView(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated, IsAdminUser, )
    authentication_classes = (JSONWebTokenAuthentication, )

Now I can access user id...but I still don't know the exact reason.

Upvotes: 1

Related Questions