python - 为什么 django.contrib.auth.authenticate() 在这里不起作用?

标签 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 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/

相关文章:

带有关键字参数的python部分

python - AWS : boto3 get all instances of a load balancers

django - 在开发期间在本地托管管理媒体

javascript - 每 30~ 分钟从服务器检索数据的最佳方法?

python - 未创建 Django 测试表

.net - 单点登录服务器/页面

python - 导入错误 : No module named base

python - rpy2:将 FloatVector 或 Matrix 转换回 Python 数组或列表?

node.js - 在 NodeJS 应用程序中存储远程 API 的身份验证 token 的最佳方法是什么?

python - 如何使用 apache 网络服务器管理与 mod_wsgi 的 session ?