Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the current user with Django Rest Framework

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?

like image 750
Maxime Avatar asked Apr 02 '13 17:04

Maxime


People also ask

Who is using Django REST Framework?

Who uses Django REST framework? 337 companies reportedly use Django REST framework in their tech stacks, including Robinhood, UpstageAI, and BirdView.

What is Restapi in Django?

REST APIs are an industry-standard way for web services to send and receive data. They use HTTP request methods to facilitate the request-response cycle and typically transfer data using JSON, and more rarely - HTML, XML and other formats.

How do I update user details in Django REST Framework?

Open auth/urls.py and add update profile endpoint. we should send a PUT request to API for checking update profile endpoint. We must add username, first_name, last_name and email. If fields passed validations, user profile will be changed.

How do you check if user is logged in react Django?

To check if a user is logged in with Python Django, we can use the request. user. is_authenticated property in our view. to check if the current user is authenticated with request.


1 Answers

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.

like image 170
Tom Christie Avatar answered Sep 18 '22 17:09

Tom Christie