为什么 django.contrib.auth.authenticate() 不在这里工作?

The*_*tus 3 python authentication django debugging

我正在编写一个简单的(目前)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")
Run Code Online (Sandbox Code Playgroud)

我得到一个属性错误:

'NoneType' 对象没有属性“first_name”。

我认为这是因为 authenticate() 返回 None (表示没有这样的用户)。

无论我是否包含“self.testu.save()”行,这都会失败。

我还有其他测试通过,所以我不认为问题出在测试基础设施上。我可以成功创建用户并从数据库中检索他们的信息。

在 models.py 中唯一提到的 User 是:

from django.contrib.auth.models import User
Run Code Online (Sandbox Code Playgroud)

我已经阅读了很多文档,但无法弄清楚发生了什么。任何人都可以帮忙吗?提前致谢。

Wil*_*sem 5

你不能User用这样的密码创建一个对象。密码需要散列。因此,您应该使用.set_password(..)[Django-doc] 方法

class UserTestCase(TestCase):

    def setUp(self):
        self.testu = User(username="thename", first_name="thefirstname")
        self.testu.set_password("thepassword")
        self.testu.save()

    # …
Run Code Online (Sandbox Code Playgroud)