首页 > 解决方案 > 是否可以在 django 中使用两个以上的变量进行身份验证?

问题描述

我在 django 中创建了一个自定义用户模型?有很多领域,包括email, password and username. 现在我想username,password and email在登录时使用身份验证。我该怎么做?

标签: django

解决方案


您必须创建自定义身份验证后端。

from django.db.models import Q

from django.contrib.auth import get_user_model

user = get_user_model()

class UsernameAndEmailBackend(object):
    def authenticate(self, username=None, password=None, **kwargs):
       email = kwargs.get('email')
       if email is None or username is None:
            return None
       try:
            user = MyUser.objects.get(username=username, email=email)
            if user.check_password(password):
                return user
       except MyUser.DoesNotExist:
            return None

然后,在您的 settings.py 中将 AUTHENTICATION_BACKENDS 设置为您的身份验证后端:

 AUTHENTICATION_BACKENDS = ('path.to.UsernameAndEmailBackend,)\

推荐阅读