Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change the field name of Serialzed User Model on frontend in Django Rest Framework?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading