一、
在settings.py 文件中的#Application definition 下增加代码:
AUTHENTICATION_BACKENDS=( 'users.views.CustomBackend' , )
注意上面的括号里,别忘了加逗号!
二、
在users/views.py中加代码:
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from .models import UserProfile class CustomBackend(ModelBackend):
"""邮箱也能登录"""
def authenticate(self, request, username=None, password=None, **kwargs):
try:
user=UserProfile.objects.get(Q(username=username)|Q(email=username))
if user.check_password(password):
return user
except Exception as e:
return None