2015-11-26 75 views
0

我試圖讓當前的用戶模型中的串行self.context [「請求」]。用戶總是返回AnonymousUser

self.context['request'].user 

但它總是返回AnonymousUser。 這裏是串行代碼片斷

class QuestionBlockDetailSerializer(serializers.ModelSerializer): 
    isvoted = serializers.SerializerMethodField(read_only=True) 

    def get_isvoted(self,obj): 
     user = self.context['request'].user 
     print self.context['request'].user 
     ... 

下面是設置權限和AuthBackends

AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend', 
'social.backends.google.GoogleOAuth2', 
'social.backends.facebook.FacebookOAuth2',) 

'DEFAULT_AUTHENTICATION_CLASSES': (
    'oauth2_provider.ext.rest_framework.OAuth2Authentication', 
    'rest_framework_social_oauth2.authentication.SocialAuthentication', 
    'rest_framework.authentication.TokenAuthentication', 

), 

觀點:

class QuestionBlockDetailAPI(generics.RetrieveAPIView, mixins.UpdateModelMixin, mixins.DestroyModelMixin): 
    permission_classes =[IsAuthenticatedOrReadOnly] 
    serializer_class = QuestionBlockDetailSerializer 
    queryset= Question_Block.objects.all() 
    lookup_field = 'q_slug' 

    def delete(self, request, *args, **kwargs): 
    return self.destroy(request,*args, **kwargs) 

    def put(self, request, *args, **kwargs): 
    return self.update(request,*args,**kwargs) 

我嘗試添加的會話和BasicAuthentication但它總是返回AnonymousUser。請幫助我。

+0

你能證明你的觀點:

你可以通過改變你def get_isvoted(self,obj):方法類似解決這個問題? –

回答

0

您在QuestionBlockDetailAPI視圖中使用IsAuthenticatedOrReadOnly權限類。所以未經身份驗證的用戶可以讀取您的API。因此,當未經身份驗證的用戶訪問您的api時,self.context['request'].user是AnonymousUser。

def get_isvoted(self,obj): 
    if self.context['request'].user.is_authenticated(): 
     return self.context['request'].user.isvoted 
    else: 
     return False 
+0

我也獲得匿名認證的用戶。我使用oAuth進行令牌認證。我嘗試了上面的代碼片段。它仍然返回anonymousUser – ashok

相關問題