I am trying to login in Django and I have seen that by default I can only log in with the username and password but due to the demands of my client he wants to be able to log in with the email apart from the username.
I have created a function from the one that comes in Django to validate the accounts but I have an error that I do not understand.
The function is:
from django.contrib.auth import login
def login_user (request):
if request.user.is_authenticated():
return redirect('home')
else:
message = None
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
username = request.POST['username']
password = request.POST['password']
if '@' in username:
kwargs = {'email': username}
else:
kwargs = {'username': username}
try:
user = User.objects.get(**kwargs)
if user.check_password(password):
if user.is_active:
login(request, user)
return redirect('home')
except User.DoesNotExist:
form = LoginForm()
return redirect('home')
Sending the request to Django's login() function gives this error:
You have multiple authentication backends configured and therefore must provide the
backend
argument or set thebackend
attribute on the user.
setting:
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'social_core.backends.open_id.OpenIdAuth',
'social_core.backends.google.GoogleOpenId',
'social_core.backends.google.GoogleOAuth2',
'social_core.backends.google.GoogleOAuth',
'social_core.backends.facebook.FacebookOAuth2',
'social_core.backends.facebook.FacebookAppOAuth2',
'social_core.backends.instagram.InstagramOAuth2',
'rest_framework_social_oauth2.backends.DjangoOAuth2')
Create your own backend method like so:
And determine the backend in the settings.py:
Inheriting from ModelBackend allows you to use the methods you see in the function, such as user.check_password(password)