使用用户名和电子邮件对用户进行身份验证

Authenticate users with both username and email

我已经用电子邮件和其他字段扩展了 UserCreationForm,这样我就可以使用用户名和电子邮件对用户进行身份验证。

forms.py:

class UserCreationForm(UserCreationForm):

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'username', 'email',)

views.py:

def auth_view(request):
    username = request.POST.get('username','')
    password = request.POST.get('password','')
    user = auth.authenticate(username=username, password=password)

    if user is not None:
        auth.login(request, user)
        return HttpResponseRedirect('/')
    elif:
        user = auth.authenticate(email=username, password=password)
        if user is not None:
            auth.login(request, user)
            return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/accounts/invalid_login')

html:

<form action="/accounts/auth/" method="post">
    {%csrf_token%}

    <label for="name">Email or Username:</label>
    <input type="text" name="name" id="name" value="">
    <label for="password">Password:</label>
    <input type="password" name="password" id="password" value="">

    <input type="submit" value="LOGIN">
</form>

在视图中,我尝试将 usernameemail 作为表单的输入作为 name,并检查用户名和密码是否经过验证。如果不是,则检查电子邮件和密码是否经过身份验证。但它不起作用。我该如何解决这个问题?请帮助我。谢谢。

您需要创建一个身份验证后端:这是我的:

class EmailAuthBackend(ModelBackend):
    """
    Email Authentication Backend

    Allows a user to sign in using an email/password pair, then check
    a username/password pair if email failed
    """

    def authenticate(self, username=None, password=None):
        """ Authenticate a user based on email address as the user name. """
        try:
            user = User.objects.get(email=username)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            try:
                user = User.objects.get(username=username)
                if user.check_password(password):
                    return user
            except User.DoesNotExist:
                return None

    def get_user(self, user_id):
        """ Get a User object from the user_id. """
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

然后在您的设置中:

AUTHENTICATION_BACKENDS = ('MyApp.backends.EmailAuthBackend',)

然后创建一个使用身份验证功能的自定义视图。