Reputation: 1604
I am using django Django=2.1.7 and rest framework djangorestframework=3.9.2 This is my url for login
path('rest-auth/login', include('rest_auth.urls')),
When I enter username and password I got the token from rest API. But I want my user detail like name, id etc to show in my react components. Please help me how to achieve. I have seen many answers on StackOverflow even the official documentation is not descriptive https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
Upvotes: 0
Views: 1919
Reputation: 414
If you use rest-auth you can get the id, username, email, first_name and last_name of the logged user using this URL: http://localhost:8000/rest-auth/user/
Upvotes: 2
Reputation: 88689
The mentioned package provides us the ability to override the settings
In the login process, the response comes from either TOKEN_SERIALIZER
or JWT_SERIALIZER
. In your case, I assume that you are not using the JWT method.
So, create a new serializer class as per your desired structure and wire it up using REST_AUTH_SERIALIZERS
settings dictionary.
Here is one sample
#serializer.py
from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.authtoken.models import Token
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ('id', 'username', 'email')
class MyCustomTokenSerializer(serializers.ModelSerializer):
user = UserSerializer(read_only=True)
class Meta:
model = Token
fields = ('key', 'user')
and in your settings.py
,
REST_AUTH_SERIALIZERS = {
'TOKEN_SERIALIZER': 'path.to.custom.MyCustomTokenSerializer',
...
...
}
Upvotes: 1
Reputation: 1079
There is no way to automatically populate user data once a user logs in. You should just be able to take the username the user entered during the login process, save it in a variable, and after receipt of token make another API call to get the user information.
Upvotes: -1