1.自定义用户登录认证类
def get_user_by_account(account):
"""
自定义 手机号和用户名都可以登录
"""
try:
if re.match('^1[3-9]\d{9}$', account):
user = UserProfile.objects.get(phone=account)
else:
user = UserProfile.objects.get(username=account)
except UserProfile.DoesNotExist:
return None
else:
return user
class UsernameMobileAuthBackend(ModelBackend):
"""
自定义用户名或手机号认证
"""
def authenticate(self, request, username=None, password=None, **kwargs):
user = get_user_by_account(username)
if user is not None and user.check_password(password):
return user
2.在settings.py中添加
AUTHENTICATION_BACKENDS = [
'users.utils.UsernameMobileAuthBackend',
]