Multiple login fields in django user

后端 未结 1 1679
孤独总比滥情好
孤独总比滥情好 2021-01-03 06:26

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.

相关标签:
1条回答
  • 2021-01-03 06:46

    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/

    0 讨论(0)
提交回复
热议问题