1

I would like to log in pages with both username and email, I wrote a CustomBackend view to auth no matter how I changed, only username works, I use "email" to log in pages, always got error ofUnable to log in with provided credentials, partial code of views.py as below:

from django.contrib.auth import get_user_model

MyUser = get_user_model()

class CustomBackend(object):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = MyUser.objects.get(Q(username=username)|Q(email=username))
            if user.check_password(password):
                return user

        except MyUser.DoesNotExist:
            MyUser().set_password(password)

partial code of settings.py as below:

AUTHENTICATION_BACKENDS = (
    'general.views.CustomBackend',
    'django.contrib.auth.backends.ModelBackend'
)

Any ideas will be highly appreciated.

  • you need to add custom model for `user` and specify `USERNAME_FIELD = 'email'` – Aarif Mar 21 '19 at 08:11
  • 1
    Thanks for your quick reply, as far as know, `USERNAME_FIELD = 'email'` can't log in with both 'username' and 'email', only `email`, I wanna two fields –  Mar 21 '19 at 08:15
  • Your code looks good so you’ll need to debug more in detail. Set a breakpoint in your authenticate method and check where it’s failing. Or add print statements to know which path is being followed. – dirkgroten Mar 21 '19 at 08:29
  • Maybe you can get some help from the answers to this question: https://stackoverflow.com/questions/25316765/log-in-user-using-either-email-address-or-username-in-django – Sanip Mar 21 '19 at 09:58

0 Answers0