0

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.

David Buck
  • 3,752
  • 35
  • 31
  • 35
Berry
  • 2,143
  • 4
  • 23
  • 46
  • `request.user.is_authenticated()` Missing `()` – anupsabraham Aug 28 '17 at 05:35
  • That's not the issue, and it still worked even without the (). – Berry Aug 28 '17 at 06:06
  • 1
    Have you set `DEFAULT_AUTHENTICATION_CLASSES` in settings? You may want this: `REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ) }` Taken from [here](http://www.django-rest-framework.org/api-guide/authentication/#how-authentication-is-determined) – Zevgon Aug 28 '17 at 06:09
  • `is_authenticated` is a method. If you try `bool(is_authenticated)` it will always return `True`. So if you use `if request.user.is_authenticated` in your code, it will always be `True`. You need to call the method using `()` to get the intended result. – anupsabraham Aug 28 '17 at 06:09
  • The third comment is the solution. Thank you very much. – Berry Aug 28 '17 at 06:11

2 Answers2

1

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',
    )
}

Taken from here

Zevgon
  • 556
  • 4
  • 13
0

You can just try request.user.is_authenticated as it is. Why do you want to try it in api view and view? Please explain.

Edit: Okay. Actually you must first use request.user.is_authenticated and then only use request.user And yes, there is no need to add () in is_authenticated bcoz it is not a function anymore in django 1.11. It is an attribute.

Gayathri
  • 140
  • 11