2017-08-28 32 views
0

is_authenticated我進行這個測試:Allauth request.user是AnonymousUser在APIView,但鑑於

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

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

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

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

第二個不能正常加載,因爲一個AssertionError的。但是,這兩個請求中的user.user發生了變化,其中APIView會打印AnonymousUser,第二個會打印登錄的實際用戶。

我正在使用Facebook登錄驗證。

+0

採取'request.user.is_authenticated()''失蹤()' – anupsabraham

+0

這不是問題,它甚至還沒有工作的()。 – Berry

+1

您是否在設置中設置了「DEFAULT_AUTHENTICATION_CLASSES」?您可能希望這樣: 'REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework.authentication.SessionAuthentication', ) }' 從[這裏]摘自(HTTP://www.django-rest-framework .org/api-guide/authentication /#how-authentication-is-determined) – Zevgon

回答

1

把答案在這裏,因爲它看起來凌亂評論:

你有沒有設置在設置DEFAULT_AUTHENTICATION_CLASSES?您可能希望這樣:

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

here

0

您可以按照原樣嘗試request.user.is_authenticated。爲什麼你想在api視圖和視圖中嘗試它?請解釋。

編輯: 好的。其實你必須首先使用request.user.is_authenticated,然後只使用request.user 是的,沒有必要在is_authenticated bcoz中添加(),它不再是在django 1.11中的函數。這是一個屬性。

+0

APIView適用於REST API。視圖用於標準渲染視圖。 – Berry