django默认后台user只能通过用户名登录,现在需求需要能够通过用户名或者邮箱登录,那就需要自定义后台验证了
具体步骤是:
1.自定义后台验证
2.在设置启用
1.重写authenticate方法,如果验证通过返回User对象
ModelBackend为django默认的后台登录,先继承此后台,只需重写auth即可
class CustomBackend(ModelBackend):
# 重写authenticate方法
def authenticate(self, request, username=None, password=None, **kwargs):
# 重点就是这一句了
user = User.objects.filter(Q(username=username) | Q(email=username)).first()
if user:
if user.check_password(password):
return user
return None
注意上面的User是通过get_user_model得到的
from django.contrib.auth import get_user_model
User = get_user_model()
2.在settings中设置
AUTHENTICATION_BACKENDS = (
'path.path.CustomBackend',
)
tips:
django默认后台为(‘django.contrib.auth.backends.ModelBackend’,)
不设置即为默认值
参考文档:
https://yiyibooks.cn/xx/django_182/topics/auth/customizing.html
https://docs.djangoproject.com/en/2.0/topics/auth/customizing/