While using Django user is it possible somehow to use multiple login fields? Like in Facebook where we can login using username, email as well as the phone number.
Yes, it is! You can write your own authentication backend, as this section describes: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/
We suppose you have created an application account/ where you extend the User model for the additional phone field. Create your auth backend backends.py inside account/ and write you own authentication logic. For example:
from account.models import UserProfile
from django.db.models import Q
class AuthBackend(object):
supports_object_permissions = True
supports_anonymous_user = False
supports_inactive_user = False
def get_user(self, user_id):
try:
return UserProfile.objects.get(pk=user_id)
except UserProfile.DoesNotExist:
return None
def authenticate(self, username, password):
try:
user = UserProfile.objects.get(
Q(username=username) | Q(email=username) | Q(phone=username)
)
except UserProfile.DoesNotExist:
return None
return user if user.check_password(password) else None
Put you custom backend in you project's settings.py:
AUTHENTICATION_BACKENDS = ('account.backends.AuthBackend',)
Then just authenticate by passing username, email or phone in the POST's username field.
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
# Redirect to a success page.
else:
# Return a 'disabled account' error message
...
else:
# Return an 'invalid login' error message.
...
see: https://docs.djangoproject.com/fr/1.8/topics/auth/default/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With