Python 为什么不是';t django.contrib.auth.authenticate()在这里工作吗?
我正在编写一个简单的(目前)Django应用程序。我在身份验证方面遇到了问题:我试图使用所有现成的组件,无论是在应用程序本身还是在测试中,我都无法对用户进行身份验证。例如,这里有一个失败的测试:Python 为什么不是';t django.contrib.auth.authenticate()在这里工作吗?,python,django,authentication,debugging,Python,Django,Authentication,Debugging,我正在编写一个简单的(目前)Django应用程序。我在身份验证方面遇到了问题:我试图使用所有现成的组件,无论是在应用程序本身还是在测试中,我都无法对用户进行身份验证。例如,这里有一个失败的测试: from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.test import TestCa
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”对象没有属性“first_name”
我认为这是因为authenticate()返回None(表示没有这样的用户)
无论我是否包含行“self.testu.save()”,这都会失败
我还有其他通过的测试,所以我认为问题不在于测试基础设施。我可以成功地创建用户并从数据库中检索他们的信息
models.py中唯一提到的用户是:
from django.contrib.auth.models import User
我已经阅读了很多文档,但不知道发生了什么。有人能帮忙吗?提前感谢。您不能用这样的密码创建
用户
对象。密码需要散列。因此,您应该使用:
类UserTestCase(TestCase):
def设置(自):
self.testu=User(username=“thename”,first\u name=“thefirstname”)
self.testu.set_密码(“密码”)
self.testu.save()
#…
class UserTestCase(TestCase):
def setUp(self):
self.testu = User(username="thename", first_name="thefirstname")
self.testu.set_password("thepassword")
self.testu.save()
# …