- 首先在setting中设置变量:
# 设置邮箱和用户名和手机号均可登录
AUTHENTICATION_BACKENDS = (
'users.views.CustomBackend',
)
- 在user/view中
定义用户可以使用用户名与手机号进行登录
class CustomBackend(ModelBackend):
"""
自定义用户验证规则
"""
def authenticate(self, username=None, password=None, **kwargs):
try:
# 不希望用户存在两个,get只能有一个。两个是get失败的一种原因
# 后期可以添加邮箱验证
user = User.objects.get(
Q(username=username) | Q(mobile=username))
# django的后台中密码加密:所以不能password==password
# UserProfile继承的AbstractUser中有def check_password(self,
# raw_password):
if user.check_password(password):
return user
except Exception as e:
return None