Search code examples
python-3.xdjango-usersdjango-3.0django-contrib

How do I lookup a user by username using Django's auth.contrib module?


I'm using Django 3.2 with Django Rest Framework 3.12.2 and django.contrib.auth. I have created a couple of super users on the command line like so

python manage.py createsuperuser --username=joe [email protected]

This creates entries in the "auth_user" table that is auto-generated by migrations. I'm curious how I lookup a user after authentication using django.contrib.auth method calls. I have this serializer I use to login a user and issue a JWT

class UserLoginSerializer(serializers.Serializer):

    username = serializers.CharField(max_length=255)
    password = serializers.CharField(max_length=128, write_only=True)
    token = serializers.CharField(max_length=255, read_only=True)

    def validate(self, data):
        username = data.get("username", None)
        password = data.get("password", None)
        user = authenticate(username=username, password=password)
        if user is None:
            raise serializers.ValidationError(
                'A user with this email and password is not found.'
            )
        try:
            payload = JWT_PAYLOAD_HANDLER(user)
            jwt_token = JWT_ENCODE_HANDLER(payload)
            update_last_login(None, user)
        except User.DoesNotExist:
            raise serializers.ValidationError(
                'User with given email and password does not exists'
            )
        return {
            'username':user.username,
            'token': jwt_token
        }

I would like to have an endpoint where I can lookup info about the user from the auth_user table.

class UserProfileView(RetrieveAPIView):

    permission_classes = (IsAuthenticated,)
    authentication_class = JSONWebTokenAuthentication

    def get(self, request):
        try:
            token = get_authorization_header(request).decode('utf-8')
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY)
            username = decoded['username']
                # how to lookup the user at this point?
            status_code = status.HTTP_200_OK
            response = {
                'success': 'true',
                'status code': status_code,
                'message': 'User profile fetched successfully',
                'data': {
                        #...
                    }
                }

After I retrieve the username, what's the proper way to lookup the user in the db using the auth.contrib module?


Solution

  • you can get the user instance by using below line of code

    from django.contrib.auth.models import User
    
    User.objects.get(username=username_from_request)
    

    if you have a custom user model or profile model with username field, use that model in place of User