Django Rest Framework在登录或注册后返回用户资料和api token。

问题描述 投票:0回答:1

我有以下的序列器。

from rest_framework import serializers
from allauth.account import app_settings as allauth_settings
from allauth.utils import email_address_exists
from allauth.account.adapter import get_adapter
from allauth.account.utils import setup_user_email
from kofiapi.api.users.models import User, UserProfile

class UserProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserProfile
        fields = ('dob', 'phone', 'receive_newsletter')


class UserSerializer(serializers.HyperlinkedModelSerializer):

    profile = UserProfileSerializer(required=True)

    class Meta:
        model = User
        fields = ('url', 
                  'email', 
                  'first_name', 
                  'last_name',
                  'password',
                  'profile')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        profile_data = validated_data.pop('profile')

        password = validated_data.pop('password')

        user = User(**validated_data)
        user.set_password(password)
        user.save()

        UserProfile.objects.create(user=user, **profile_data)

        return user

    def update(self, instance, validated_data):

        profile_data = validated_data.pop('profile')
        profile = instance.profile

        instance.email = validated_data.get('email', instance.name)
        instance.save()

        profile.dob = profile_data.get('dob', profile.dob)
        profile.phone = profile_data.get('phone', profile.phone)
        profile.receive_newsletter = profile_data.get('receive_newsletter', profile.receive_newsletter)
        profile.save()

        return instance

而这些是我所拥有的各自路线

router = DefaultRouter()
router.register(r"users", UserViewSet)

urlpatterns = [
    path('', include(router.urls)),

    path('rest-auth/', include('rest_auth.urls')),
    #path('rest-auth/registration/', include('rest_auth.registration.urls')),
]

我使用的是:

'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',

configured as:

AUTH_USER_MODEL = 'users.User'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ),
}

当我登录时,我只得到了令牌密钥。

{
    "key": "8c0d808c0413932e478be8882b2ae829efa74b3e"
}

我怎么能让它在注册登录时返回用户信息和密钥?类似于

{ "key": "8c0d808c0413932e478be8882b2ae829efa74b3e", "user": { /用户数据 }}。

django python-3.x django-rest-framework django-rest-auth
1个回答
1
投票

你需要在views.py中创建一个自定义的Auth类,像这样。

class CustomAuthToken(ObtainAuthToken):

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({
            'token': token.key,
            'user_id': user.pk,
            'email': user.email
        })

在你的urls.py中,添加以下内容将你的认证URL路由到你新创建的认证类。

url('your-auth-url', CustomAuthToken.as_view())

1
投票

设置 TOKEN_SERIALIZER 设置为:

#serializers.py
from rest_auth.serializers import TokenSerializer
from django.contrib.auth import get_user_model


class UserTokenSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ('id', 'email')


class CustomTokenSerializer(TokenSerializer):
    user = UserTokenSerializer(read_only=True)

    class Meta(TokenSerializer.Meta):
        fields = ('key', 'user')


#settings.py
REST_AUTH_SERIALIZERS = {
    'TOKEN_SERIALIZER': 'path.to.custom.CustomTokenSerializer',

}

参考资料

© www.soinside.com 2019 - 2024. All rights reserved.