我正在使用Django 3.1,并试图弄清楚为什么未调用我的自定义身份验证后端。
在我的settings.py文件中,我有:
AUTHENTICATION_BACKENDS = (
'sizzy.backends.EmailBackend',
)
在我的sizzy.backends.py文件中,我有:
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.backends import ModelBackend
from .models import User
class EmailBackend(ModelBackend):
def authenticate(self, username=None, password=None):
try:
print("Trying the email backend!")
user = User.objects.get(email=username)
print("Got the user")
if user.check_password(password): # check valid password
return user
print("password didn't work")
except ObjectDoesNotExist:
return None
def get_user(self, user_id):
try:
print("Getting the user of the Email Bkacned")
return User.objects.get(pk=user_id)
except ObjectDoesNotExist:
return None
然后我打开manage.py shell
并输入:
from django.contrib.auth import authenticate
email = "billypop@a.pop"
password = "password"
user = authenticate(username=email, password=password)
它输出:
Login failed. Credentials:
{'username': 'billypop@a.pop', 'password': '********************'}
我没有看到任何打印说明。 “试图获取电子邮件后端!”永远不会打印。我想念什么吗?我尝试将设置文件更改为指向sizzy.backends.EmailBackendqwertyui
,以进行健全性检查,但这引发了错误,而不是登录失败。因此后端正在以某种方式加载,但从未调用过。
我还尝试将ModelBackend更改为BaseBackend,结果相同。
答案 0 :(得分:1)
authenticate(...)
方法的 功能签名 似乎不正确,应该为
class EmailBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
# do something