self.context [' request']。用户始终返回AnonymousUser

时间:2015-11-26 00:52:02

标签: django django-rest-framework django-authentication

我正在尝试在模型序列化器中获取当前用户

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)

我尝试添加Session和BasicAuthentication但它总是返回AnonymousUser。请帮帮我。

2 个答案:

答案 0 :(得分:0)

您在IsAuthenticatedOrReadOnly视图中使用QuestionBlockDetailAPI权限类。因此,未经过身份验证的用户可以读取您的API。因此,当未经身份验证的用户访问您时,self.context['request'].user是AnonymousUser。

您可以通过更改def get_isvoted(self,obj):方法来解决此问题:

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

答案 1 :(得分:0)

仅在有条件的情况下使用user.is_authenticated

if self.context['request'].user.is_authenticated:
    return true