我正在编写一个简单的(目前)Django 应用程序。我在身份验证方面遇到问题:我正在尝试使用所有开箱即用的组件,但在应用程序本身和测试中,我无法对用户进行身份验证。例如,这是一个失败的测试:
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.test import TestCase
[...]
class UserTestCase(TestCase):
def setUp(self):
self.testu = User(username="thename", password="thepassword", first_name="thefirstname")
self.testu.save()
def testAuthenticate(self):
u = authenticate(username="thename", password="thepassword")
self.assertEqual(u.first_name, "thefirstname")
我收到一个属性错误:
'NoneType' object has no attribute "first_name".
我认为这是因为authenticate()返回None(表示没有这样的用户)。
无论我是否包含“self.testu.save()”行,都会失败。
我还有其他测试通过,所以我认为问题不在于测试基础设施。我可以成功创建用户并从数据库中检索他们的信息。
models.py 中唯一提及 User 的是:
from django.contrib.auth.models import User
我已经阅读了很多文档,但无法弄清楚发生了什么。有人可以帮忙吗?提前致谢。
最佳答案
您无法使用这样的密码创建User
对象。密码需要散列。因此,您应该使用.set_password(..)
method [Django-doc] :
class UserTestCase(TestCase):
def setUp(self):
self.testu = User(username="thename", first_name="thefirstname")
self.testu<b>.set_password(</b>"thepassword"<b>)</b>
self.testu.save()
# …
关于python - 为什么 django.contrib.auth.authenticate() 在这里不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60755947/