DRF Simple JWT functions RefreshToken.for_user(user) get Attribute error with Custom User Model

16 Views Asked by At

I create a custom User Model with usercode is PrimaryKey

class User(AbstractBaseUser, PermissionsMixin):
    usercode = models.CharField(primary_key=True, unique=True, null=False)
    username = models.CharField(max_length=255, unique=True, null=True, blank=True, default=None)
    email = models.EmailField(unique=True, null=True, blank=True, default=None)
    phone_number = models.CharField(max_length=128, unique=False, null=True, blank=True, default=None)
    password = models.CharField(max_length=256, null=False)
        ...

I replace default TokenObtainPairView serialier of SimpleJWT with and work quite good

class CustomTokenObtainPairSerializer(serializers.Serializer):
    usercode = serializers.CharField(max_length=64)
    password = serializers.CharField(max_length=255)

    def validate(self, attrs):
        usercode = attrs['usercode'].upper()
        password = attrs['password']

        # Get user object for validating
        user = User.objects.filter(usercode=usercode).first()
        # Validating login request
        if user is None:
            raise AuthenticationFailed(f'User not found!')
        if not check_password(password, user.password):
            return Response({'message': 'Wrong password!'})
        user_data = UserSerializer(user).data
        tokens = get_tokens_for_user(user)

        return {'user': user_data, 'tokens': tokens}

class CustomTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer


def get_tokens_for_user(user):
    refresh = RefreshToken.for_user(user)

    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }

But when I try to get custom token like source Creating tokens manually I got error at RefreshToken.for_user(user) Errors details:

AttributeError at /application/api/v1/2024/token/
'User' object has no attribute 'id'
Request Method: POST
Request URL:    http://127.0.0.1:8000/application/api/v1/2024/token/
Django Version: 5.0.3
Exception Type: AttributeError
Exception Value: 'User' object has no attribute 'id'

I checked and got that the RefreshToken.for_user require a User model with id is PrimaryKey

File "D:\development\py\DJ_Project\venv\Lib\site-packages\rest_framework_simplejwt\tokens.py", line 203, in for_user
    user_id = getattr(user, api_settings.USER_ID_FIELD)

I'm finding solution to replace 'id' to 'usercode' or other custom primary key without using default 'id'. Can someone help.

0

There are 0 best solutions below