I am making a simple Login/Logout App using REST API in Django DRF. I am using the default User model for this behavior.
In the Login API, I wanted to authenticate the user with email, hence I wrote the custom authentication using ModelBackend. Everything works fine.
But, I want to change the word username to email in the front of the Login API. I tried using the source attribute, but it does not change. Is there any easy way to do it? I am looking for something like verbose_name, that is used in Django Models.
My serializers.py is:
class LoginSerializer(serializers.Serializer):
username = serializers.CharField(source='Email')
password = serializers.CharField()
def validate(self, data):
user = authenticate(**data)
if user and user.is_active:
return user
raise serializers.ValidationError('Incorrect Credentials Passed.')
Again, I am using the default User Model, and I don’t want to overwrite/override/extend the User Model. I just want to change the name of the field username on the frontend to be shown as email.
Any help will surely be appreciated.
>Solution :
You need to pass a value called email and not username to your ModelBackend subclass:
class LoginSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, data):
user = authenticate(**{'email': data['username'], 'password': data['password']})
if user and user.is_active:
return user
raise serializers.ValidationError('Incorrect Credentials Passed.')