[Django]-Django Rest Framework return user profile along with api token after login or registration

5👍

set TOKEN_SERIALIZER settings as,

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

}

Reference

👤JPG

1👍

You need to create a custom Auth Class in your views.py like this:

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

And in your urls.py, add this to route your Authentication URL to you newly made authentication class:

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

Leave a comment