0
votes

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

3
Can you show the package you are using? (rest_auth)?JPG

3 Answers

1
votes

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/

1
votes

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',
    ...
    ...
}
-1
votes

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.