Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After login the `rest-auth`, how to return more information?

I use django-rest-auth in my Django project.

After login the rest-auth/login/, how to return more information?

In the rest-auth/login/, when I login the user, it returns a key.

enter image description here

I want to also return the user's information, how can I get this?

like image 986
aircraft Avatar asked Jan 18 '18 05:01

aircraft


2 Answers

Please refer to this link

You can override the default TokenSerializer with a custom serializer that will include users.

in a file say yourapp/serializers.py

from django.conf import settings

from rest_framework import serializers
from rest_auth.models import TokenModel
from rest_auth.utils import import_callable
from rest_auth.serializers import UserDetailsSerializer as DefaultUserDetailsSerializer

# This is to allow you to override the UserDetailsSerializer at any time.
# If you're sure you won't, you can skip this and use DefaultUserDetailsSerializer directly
rest_auth_serializers = getattr(settings, 'REST_AUTH_SERIALIZERS', {})
UserDetailsSerializer = import_callable(
    rest_auth_serializers.get('USER_DETAILS_SERIALIZER', DefaultUserDetailsSerializer)
)

class CustomTokenSerializer(serializers.ModelSerializer):
    user = UserDetailsSerializer(read_only=True)

    class Meta:
        model = TokenModel
        fields = ('key', 'user', )

and in your app settings use rest-auth configuration to override the default class

yourapp/settings.py

REST_AUTH_SERIALIZERS = {
    'TOKEN_SERIALIZER': 'yourapp.serializers.CustomTokenSerializer' # import path to CustomTokenSerializer defined above.
}
like image 110
Greko2015 GuFn Avatar answered Nov 19 '22 02:11

Greko2015 GuFn


At last, I get my solution:

class TokenSerializer(serializers.ModelSerializer):
    """
    Serializer for Token model.
    """
    user = UserInfoSerializer(many=False, read_only=True)  # this is add by myself.
    class Meta:
        model = TokenModel
        fields = ('key', 'user')   # there I add the `user` field ( this is my need data ).

In the project settings.py, add the TOKEN_SERIALIZER like bellow:

REST_AUTH_SERIALIZERS = {
    ...
    'TOKEN_SERIALIZER': 'Project.path.to.TokenSerializer',
}

Now I get my need data:

enter image description here

like image 31
aircraft Avatar answered Nov 19 '22 01:11

aircraft