django - 是否可以在 django 中使用两个以上的变量进行身份验证?
问题描述
我在 django 中创建了一个自定义用户模型?有很多领域,包括email, password and username
. 现在我想username,password and email
在登录时使用身份验证。我该怎么做?
解决方案
您必须创建自定义身份验证后端。
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,)\
推荐阅读
- c# - 更改 UI 图像的精灵,保留纵横比被选中但不起作用?统一2019.1.0f2
- javascript - 解决重大错误后插件(floatThead.js)不再工作
- spring - 带有安全表达式的 @Query 上的类型期望不匹配
- typescript - 我是否需要在 TypeScript 的类和接口中注释对象属性?
- java - 带有 Apache Camel 的 Spring Boot 应用程序在启动后立即关闭
- dialog - UIPath如何自动设置用户名和密码?
- javascript - 我想打破循环
- hadoop - 如何使用 HBase 二级索引表作为 MapReduce 作业的输入?
- django - Django 不提供常见的静态文件
- excel - 过滤日期列的函数