0👍
✅
Assuming that you have already included the custom backend in AUTHENTICATION_BACKENDS
setting in settings.py
file.
You can make a condition check that whether it is a phone no. or email using regex
so:
import re
from django.contrib.auth import get_user_model
class CustomAuthBackend:
def authenticate(self, request, username=None, password=None):
UserModel = get_user_model()
# Check whether username is an email address or phone number
if re.match(r'^\+?\d{10,14}$', username):
try:
user = UserModel.objects.get(phone_number=username)
if user.check_password(password):
return user
except UserModel.DoesNotExist:
return None
else:
try:
user = UserModel.objects.get(email=username)
if user.check_password(password):
return user
except UserModel.DoesNotExist:
return None
def get_user(self, user_id):
try:
return get_user_model().objects.get(pk=user_id)
except get_user_model().DoesNotExist:
return None
1👍
I had forgotten to include request
as a parameter in authenticate
method. 🙂
Correct version:
def authenticate(self, request, username=None, password=None):
# ...
- [Answered ]-Is there another way to change the error message on a ModelForm for a validate_unique error?
- [Answered ]-Updated: How to span multile tables in Django for a backwards relationship
- [Answered ]-Django authentication : CSRF Failed
Source:stackexchange.com