Skip to main content
 首页 » 编程设计

python之Django,如何使用名字和姓氏对用户进行身份验证

2025年05月04日3052php

我想使用名字和姓氏对用户进行身份验证

这是我正在使用的代码

user = auth.authenticate(first_name=firstname,last_name=lastname,password=密码)

它不断提出 NoneType: None

我检查了名字和姓氏加上密码是否正确?

我做错了什么?谢谢

请您参考如下方法:

这里的困难在于,通常您会通过创建一个实现了 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,则可以避免此问题。