【发布时间】:2016-05-05 11:23:06
【问题描述】:
我在文件project/emailauth.py 中编写了自己的身份验证后端,内容为:
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User
class EmailBackend(object):
def authenticate(self, username=None, password=None):
print("Email auth")
try:
user = User._default_manager.get(email=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
except:
return None
def get_user(self, user_id):
try:
return User._default_manager.get(pk=user_id)
except User.DoesNotExist:
return None
我在文件末尾的project/settings.py 中添加了内容:
AUTHENTICATION_BACKENDS = (
'project.emailauth.EmailBackend',
'django.contrib.auth.backends.ModelBackend',
)
我在userprofile/views.py 中使用身份验证方法:
from django.contrib.auth import authenticate, login, logout
#...
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
profile = authenticate(username=username, password=password)
if profile is not None:
login(request, profile)
return HttpResponseRedirect(redirect_to)
#...
最有趣的是,我注意到控制台输出Email auth 只有当我尝试使用用户名和密码登录时,如果我使用电子邮件和密码,控制台中没有输出。看起来我的自定义身份验证在标准方法之后启动......
谁能告诉我哪里出错了?
【问题讨论】:
标签: python django django-authentication