Home > Blockchain >  Django Rest Framework - loginview Invalid data. Expected a dictionary, but got AnonymousUser
Django Rest Framework - loginview Invalid data. Expected a dictionary, but got AnonymousUser

Time:01-13

I am trying to code a login view in django rest framework, but I am getting this error:

Invalid data. Expected a dictionary, but got AnonymousUser.

This is my loginserializer:

class LoginSerializer(serializers.ModelSerializer):
email = serializers.EmailField(max_length=254, min_length=4)
password = serializers.CharField(max_length=68, min_length=8, write_only=True)
username = serializers.CharField(max_length=20, min_length=4, read_only=True)
tokens = serializers.CharField(max_length=700, min_length=8, read_only=True)

class Meta:
    model = UserProfile
    fields = ['email', 'password', 'username', 'tokens']

def validate(self, attrs):
    email = attrs.get('email', '')
    password = attrs.get('password', '')
    user = auth.authenticate(email=email, password=password)

    if not user:
        raise AuthenticationFailed('Invalid credentials, please try again later')

    if not user.has_verified_email:
        raise AuthenticationFailed('Your email has not been verified, please verify it and then proceed to login later.')

    if not user.is_active and user.has_verified_email:
        raise AuthenticationFailed('Your account has been disabled, please try again later')

    return {
        'email': user.email,
        'username': user.username,
        'tokens': user.tokens,
    }

    return super().validate(attrs)

This is my loginapiview:

class LoginAPIView(generics.GenericAPIView):

serializer_class = LoginSerializer

def post(self, request):
    user = request.user
    serializer = self.serializer_class(data=user)
    serializer.is_valid(raise_exception=True)

    return response.Response(serializer.data, status=status.HTTP_200_OK)

And I am also returning jwt tokens for the user model using the following function:

def tokens(self):
    refresh_token = RefreshToken.for_user(self)
    return {
        'refresh': str(refresh_token),
        'access': str(refresh_token.access_token),
    }

I crossed check everything, I am actually following a course on youtube,but I don't understand what is wrong and how I should rectify it, I would appreciate any form of advice. Thank You.

CodePudding user response:

there is mistake in this line:

serializer = self.serializer_class(data=user)

you can check use it with request.data

  •  Tags:  
  • Related