登录`rest-auth`后,如何返回更多信息?

时间:2018-01-18 05:56:13

标签: python django django-rest-auth

我在Django项目中使用django-rest-auth

登录rest-auth/login/后,如何返回更多信息?

rest-auth/login/中,当我登录用户时,它会返回key

enter image description here

我还要返回用户的信息,我该如何获取?

2 个答案:

答案 0 :(得分:5)

最后,我得到了我的解决方案:

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 ).

在项目settings.py中,添加TOKEN_SERIALIZER如下:

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

现在我得到了我的需求数据:

enter image description here

答案 1 :(得分:0)

请参阅此link

您可以使用包含用户的自定义序列化程序覆盖默认的 TokenSerializer

在文件中说 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', )

并在您的应用设置中使用 rest-auth 配置来覆盖默认类

yourapp/settings.py

REST_AUTH_SERIALIZERS = {
    'TOKEN_SERIALIZER': 'yourapp.serializers.CustomTokenSerializer' # import path to CustomTokenSerializer defined above.
}