Return the current user with Django Rest Framework

Maxime picture Maxime · Apr 2, 2013 · Viewed 36.2k times · Source

I am currently developing an API using Django.

However, I would like to create a view that returns the current User with the following endpoint: /users/current/.

To do so, I created a list view and filtered the queryset on the user that made the request. That works, but the result is a list, not a single object. Combined with pagination, the result looks way too complicated and inconsistent compared to other endpoints.

I also tried to create a detail view and filtering the queryset, but DRF complains that I provided no pk or slug.

Do you have any idea?

Answer

Tom Christie picture Tom Christie · Apr 3, 2013

With something like this you're probably best off breaking out of the generic views and writing the view yourself.

@api_view(['GET'])
def current_user(request):
    serializer = UserSerializer(request.user)
    return Response(serializer.data)

You could also do the same thing using a class based view like so...

class CurrentUserView(APIView):
    def get(self, request):
        serializer = UserSerializer(request.user)
        return Response(serializer.data)

Of course, there's also no requirement that you use a serializer, you could equally well just pull out the fields you need from the user instance.

@api_view(['GET'])
def current_user(request):
    user = request.user
    return Response({
        'username': user.username,
        'email': user.email,
        ...
    })

Hope that helps.