Search code examples
djangodjango-rest-frameworkdjango-authentication

self.context['request '].user always returns AnonymousUser


I am trying to get current user in a model serializer

self.context['request'].user

but it always returns AnonymousUser. Here is the serializer code snippet

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
        ...

Below is the settings for permissions and 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',

),

view:

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)

I tried adding Session and BasicAuthentication but it always returned AnonymousUser. Please help me on this.


Solution

  • you are using IsAuthenticatedOrReadOnly permission class in your QuestionBlockDetailAPI view. So unAuthenticated users have read access to your api. Therefore self.context['request'].user is AnonymousUser when unAuthenticated user accesses you api.

    you can solve this by changing you def get_isvoted(self,obj): method like:

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