Search code examples
pythondjangodjango-rest-frameworkdjango-rest-framework-jwt

change account authenticate method from username to email


I want to change login method from username to email.

urls.py

from rest_framework_jwt.views import obtain_jwt_token,refresh_jwt_token

urlpatterns = [
    url(r'^login/$', obtain_jwt_token),
    url(r'^tokenRefresh/', refresh_jwt_token)
]

setting.py

ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False

I have used above solution but not working for me. can you please help!!


Solution

  • That's because django-allauth has nothing to do with django-rest-framework-jwt. The settings you've set inside settings.py was belong the django-allauth so if you want to use those settings, then you should use django-allauth views.

    With django-rest-framework-jwt views, I've taken a look on obtain_jwt_token view and I've seen that they're using get_user_model().USERNAME_FIELD to get the username field.

    from django.contrib.auth import get_user_model
    
    def get_username_field():
        try:
            username_field = get_user_model().USERNAME_FIELD
        except AttributeError:
            username_field = 'username'
    
        return username_field
    

    So if you want to change username field to another one, you could create a custom User model and then set the value for USERNAME_FIELD to email to allow user to login via email instead of username. Like so:

    app_name/models.py

    from django.contrib.auth.models import AbstractUser
    from django.db import models
    
    class User(AbstractUser):
        USERNAME_FIELD = 'email'
    
        def __str__(self):
            return self.email
    

    and on your settings.py:

    AUTH_USER_MODEL = 'app_name.User'