Django中django.contrib.auth.authenticate()无法正常工作求助
解决Django原生用户认证返回None的问题
哦,这个问题我之前也碰到过!问题出在你创建测试用户的方式上——Django的User模型不会自动对你直接赋值的明文密码进行哈希处理,而authenticate()方法是需要验证哈希后的密码的,这就导致它找不到匹配的用户,返回None。
问题根源
你在setUp里直接给User实例的password字段赋值明文:
self.testu = User(username="thename", password="thepassword", first_name="thefirstname") self.testu.save()
这会把明文密码直接存在数据库里,但authenticate()会将你传入的密码哈希后,再和数据库中存储的哈希值对比。两边格式不匹配,自然验证失败,返回None,也就触发了AttributeError。
两种解决方案
方案1:使用create_user()方法创建用户(推荐)
Django提供了专门的User.objects.create_user()方法,它会自动帮你哈希密码:
def setUp(self): self.testu = User.objects.create_user( username="thename", password="thepassword", first_name="thefirstname" )
方案2:手动调用set_password()再保存
如果一定要手动实例化User对象,可以先创建实例,再调用set_password()方法处理密码,最后保存:
def setUp(self): self.testu = User(username="thename", first_name="thefirstname") self.testu.set_password("thepassword") # 这一步会哈希密码 self.testu.save()
修改后的测试效果
把setUp改成上面任意一种方式后,你的testAuthenticate测试就能正常通过了,因为此时数据库里存储的是哈希后的密码,authenticate()可以正确验证匹配。
内容的提问来源于stack exchange,提问作者Theaetetus
相关产品推荐
相关产品推荐

