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?
Who uses Django REST framework? 337 companies reportedly use Django REST framework in their tech stacks, including Robinhood, UpstageAI, and BirdView.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With