I am trying to make available the current user object so my AJAX front-end can determine if the user is logged in or not.
The current user is either an instance of dajngo.contrib.auth.User for logged in people or AnonymousUser for non-logged in people. The serializer is as follows,
class UserSerializer(serializers.HyperlinkedModelSerializer):
comments = serializers.HyperlinkedRelatedField(many = True, view_name = 'comment-detail')
class Meta:
model = User
fields = ('url', 'username', 'comments', 'first_name', 'last_name')
with the following view
class CurrentUserView(APIView):
'''
Returns the current user, logged in or not
'''
def get(self, request, *args, **kwargs):
serializer = serializers.UserSerializer(request.user)
return Response(serializer.data)
This serializer works fine for logged in users i.e. it patches on the 'comments' field and sends it off. However for AnonymousUser it chokes. It claims that there is no method 'comments' (which there isn't but it should be patched on right?) and if I remove the 'comments' requirement from fields it then complains about no 'first_name'.
Is this an issue with AnonymousUser not being an instance of django.contrib.auth.User? If so, how do I remedy it?
I realise I could check at the View level and return a custom data object if it is an instance of AnonymousUser but is there a neater way to do this?