pythondjangodjango-rest-frameworkdjango-rest-authdj-rest-auth

how to show user in TokenSerializer dj-rest-auth


I'm trying to return UserSerializer after successful login through dj-rest-auth.

I followed the steps that were told in After login the `rest-auth`, how to return more information? which has a similar issue, but it still doesn't show information about User after logging in.

what i'm getting after successful login

REST_AUTH_SERIALIZERS = {
    'TOKEN_SERIALIZER': 'blink.user.serializers.TokenSerializer',
    'USER_DETAILS_SERIALIZER': 'blink.user.serializers.UserSerializer'
}
#settings.py
class UserSerializer(serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):
        exclude_fields = kwargs.pop('exclude_fields', None)
        super(UserSerializer, self).__init__(*args, **kwargs)
        if self.context and 'view' in self.context and self.context['view'].__class__.__name__ == 'UsersView':
            exclude_fields = ['subscription', 'avatar', 'file']
        if exclude_fields:
            for field_name in exclude_fields:
                self.fields.pop(field_name)

    class Meta:
        fields = ('id', 'username', 'email', 'last_login', 'first_name', 'last_name')
        model = User

class TokenSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = TokenModel
        fields = '__all__'

#User.serializers.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from blink.common.models import Base
from django.utils.translation import gettext_lazy as _
from django.utils import timezone

class User(AbstractUser):
    username = models.CharField(
        _('username'),
        max_length=150,
        default='',
        unique=True
    )

    def __str__(self):
        return str(self.username)

    class Meta:
        db_table = 'user'
        verbose_name = _('User')
        verbose_name_plural = _('Users')
 

#user/models.py


Solution

  • I tackled my own problem, the only issue was with my settings.py

    dj-rest-auth changed the way you configure your token serializer from 3.0.0 version it works fine also for latest (6.0.0)

    REST_AUTH = {
        'TOKEN_SERIALIZER': 'blink.user.serializers.TokenSerializer',
        'USER_DETAILS_SERIALIZER': 'blink.user.serializers.UserSerializer',
    

    instead of , which worked only for dj-rest-auth <= 2.2.8 versions

    REST_AUTH_SERIALIZERS = {
        'TOKEN_SERIALIZER': 'blink.user.serializers.TokenSerializer',
        'USER_DETAILS_SERIALIZER': 'blink.user.serializers.UserSerializer'
    }