How to use another field for logging in with Django Allauth?

前端 未结 1 2022
攒了一身酷
攒了一身酷 2021-01-25 04:12

I have successfully setup django-allauth along with a custom user model which let\'s users sign in directly using email and password or through Facebook, in which c

相关标签:
1条回答
  • 2021-01-25 04:34

    The following solution worked for me. I put the code in the forms.py file.

    from allauth.account.forms import LoginForm
    from auth_project import settings
    
    class CustomLoginForm(LoginForm):
        def __init__(self, *args, **kwargs):
            super(LoginForm, self).__init__(*args, **kwargs)
            if settings.ACCOUNT_AUTHENTICATION_METHOD == "email":
                login_widget = forms.TextInput(attrs={'type': 'text',
                                                      'placeholder':
                                                      ('Mobile Number'),
                                                      'autofocus': 'autofocus'})
                login_field = forms.CharField(label=("Mobile"),
                                               widget=login_widget)
            self.fields["login"] = login_field
            set_form_field_order(self,  ["login", "password", "remember"])
    
        def user_credentials(self):
            credentials = {}
            mobile = self.cleaned_data["login"]
            login = CustomUser.objects.filter(mobile=mobile).values('email')[0]['email']
            if settings.ACCOUNT_AUTHENTICATION_METHOD == "email":
                credentials["email"] = login
            credentials["password"] = self.cleaned_data["password"]
            return credentials
    
    # this is to set the form field in order
    # careful with the indentation
    def set_form_field_order(form, fields_order):
        if hasattr(form.fields, 'keyOrder'):
            form.fields.keyOrder = fields_order
        else:
            # Python 2.7+
            from collections import OrderedDict
            assert isinstance(form.fields, OrderedDict)
            form.fields = OrderedDict((f, form.fields[f])
                                      for f in fields_order)
    

    Thanks.

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