0

I created login authentication in Rest Api it Retrieves token key in postman. Right now I need the username of the person associated with a token key.

how to do that ?

# views.py
class LoginView(APIView):

    def post(self, request):

        serializer = LoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data["user"]
        django_login(request, user)
        token, created = Token.objects.get_or_create(user=user)
        return Response({"token": token.key }, status=200)


# serializers.py
class LoginSerializer(serializers.Serializer):
        username = serializers.CharField()
        password = serializers.CharField()

        def validate(self, data):
            username = data.get("username", "")
            password = data.get("password", "")

            if username and password:
                user = authenticate(username=username, password=password)
                if user:
                    if user.is_active:
                        data["user"] = user
                    else:
                        msg = "User is deactivated."
                        raise exceptions.ValidationError(msg)
                else:
                    msg = "Unable to login with given credentials."
                    raise exceptions.ValidationError(msg)
            else:
                msg = "Must provide username and password both."
                raise exceptions.ValidationError(msg)
            return data

1 Answer 1

1

After the login authentication the method(Authentication method) will return the user, so you can fetch the user data like this,

username = user.username

Example:

class LoginView(APIView):

def post(self, request):

    serializer = LoginSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    user = serializer.validated_data["user"]
    django_login(request, user)
    token, created = Token.objects.get_or_create(user=user)
    return Response({"token": token.key , "username":user.username},status=200)
Sign up to request clarification or add additional context in comments.

4 Comments

in serializer file ?
You want to pass the username along with the token right ?
s it should print near the token after logon
can u post the code here, i cant understand iam new to programming

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.