繁体   English   中英

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

[英]Why isn't django.contrib.auth.authenticate() working here?

我正在编写一个简单的(目前)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' 对象没有属性“first_name”。

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

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

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

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

from django.contrib.auth.models import User

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

您不能使用这样的密码创建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()

    # …

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM