这里的困难在于,通常您会通过创建实现authenticate 和get_user 的自定义身份验证后端来处理此问题。但是,authenticate 的函数签名是:
def authenticate(self, username=None, password=None):
在 Django 中调用它的任何地方都只会传递 2 个参数,用户名和密码。这意味着如果以任何其他方式完成,使用任何通用身份验证表单和管理界面之类的东西都会中断。
我能看到的唯一解决方法是,如果将用户名输入为单个条目,并使用字符串“First Last”(由空格分隔)代替用户名。然后,您可以将其分离出来并使用该值...
(这都是未经测试的,但你明白了)
class FirstLastNameBackend(object):
def authenticate(self, username=None, password=None):
first, last = username.split(' ', 1)
try:
user = User.objects.get(first_name=first, last_name=last)
if user:
# Check if the password is correct
# check if the user is active
# etc., etc.
return user
except:
pass
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except:
return None
django 文档提供了很多关于自定义后端的有用细节:User auth with custom backend
在旁注中,需要注意的是其中包含空格的姓氏,例如“de la Cruz”。如果您在split 函数上为 maxsplit 指定 1,您将避免此问题。