Berry Berry - 2 months ago 16
Python Question

Allauth request.user is AnonymousUser in APIView, but is_authenticated in View

I performed this test:

class IsAuthenticatedView(APIView):
def get(self, request):
print(request.user)

return Response({
"is_authenticated": "true" if request.user.is_authenticated else "false"
}, 200)


and

class IsAuthenticatedView(View):
def get(self, request):
print(request.user)

return Response({
"is_authenticated": "true" if request.user.is_authenticated else "false"
}, 200)


The second one fails to load properly because of an AssertionError. However, the request.user changes among these two, where the APIView prints an AnonymousUser, the second prints the actual user logged in.

I'm using the Facebook login authentication.

Answer Source

Putting the answer here because it looks messy as a comment:

Have you set DEFAULT_AUTHENTICATION_CLASSES in settings? You may want this:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': ( 
        'rest_framework.authentication.SessionAuthentication',
    )
}