2

This is my current code can anyone please add the required code to allow a user to login with email or username

backends.py

from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend, UserModel class CaseInsensitiveModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: case_insensitive_username_field = '{}__iexact'.format(UserModel.USERNAME_FIELD) user = UserModel._default_manager.get(**{case_insensitive_username_field: username}) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user 

custom user models

enter image description here

enter image description here

3
  • Can you share your custom user model? Commented Sep 12, 2021 at 18:15
  • Please include code, not images of code: see this question named Why not upload images of code errors when asking a question. Please edit the question and include code fragments. Commented Sep 12, 2021 at 18:41
  • I tried adding code, but he says most of my question is code, and he won't let me save the changes. Commented Sep 12, 2021 at 18:44

1 Answer 1

2

You can make a ModelBackend that will focus on retrieving the UserModel where the USERNAME_FIELD matches, or the email field matches with the __iexact lookup [Django-doc].

from django.contrib.auth import get_user_model def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() user_field = UserModel.USERNAME_FIELD if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: case_insensitive_username_field = '{}__iexact'.format(UserModel.USERNAME_FIELD) user = UserModel._default_manager.get( Q((f'{user_field}__iexact', username)) | Q(username__iexact=username) ) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.