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

12

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

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

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

enter image description here

我想要返回用户的信息,怎么做呢?


请使用request.user或打印并检查。 - Anup Yadav
@AnupYadav 我使用第三方的 rest-auth 库,对我来说没有视图。视图由 rest-auth 控制。 - aircraft
你可以使用 https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html 获取所有信息,或者为每个OAuth构建自定义库,例如Google OAuth https://github.com/anupy/google-oauth。对于其他服务提供商,您可以使用自己的(自定义)库。 - Anup Yadav
这个链接是关于django-rest-framework-social-oauth2的,我觉得这个也不错。 - Anup Yadav
2个回答

14

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

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',
}

现在我已经得到了所需的数据:

输入图像描述


2
请参考此链接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.
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接