Python Django Testing-authenticate()返回无
正在使用Django进行一些单元测试,并尝试使用登录表单对登录过程进行一些测试 我使用修改的Python Django Testing-authenticate()返回无,python,django,unit-testing,authentication,Python,Django,Unit Testing,Authentication,正在使用Django进行一些单元测试,并尝试使用登录表单对登录过程进行一些测试 我使用修改的用户模型只是为了使电子邮件字段唯一;否则就没有什么大的不同 account/views.py 帐户/测试视图.py account/models.py 项目/设置.py 有趣的是,登录在web应用程序上正常工作,但测试时总是返回None 我试图对创建的用户检查\u password(),它在test方法和view方法中都返回true 我也尝试过使用身份验证\u BACKEND=['django.contr
用户
模型只是为了使电子邮件字段唯一;否则就没有什么大的不同
account/views.py
帐户/测试视图.py
account/models.py
项目/设置.py
有趣的是,登录在web应用程序上正常工作,但测试时总是返回None
我试图对创建的用户检查\u password()
,它在test方法和view方法中都返回true
我也尝试过使用
身份验证\u BACKEND=['django.contrib.auth.backends.modelbend']
,但没有成功。我也遇到了同样的问题。问题出现在is\u active
model字段中。在我的例子中,此字段默认为False
,因此authenticate()
始终返回None
。您正在创建一个CustomUser
,但您正在使用account.User
作为AUTH\u User\u MODEL
。两者都是相同的东西,以不同的名称导入吗?是的,它是在一个别名下导入的,但是将CustomUser恢复为User仍然会得到相同的结果。我将更新显示别名的代码。不知何故,我能够解决这个问题,但我不确定是什么解决了这个问题。抱歉,如果这对任何可能有类似问题的人都没有帮助。
def post(self, request):
# Retrieve the username and password
username = request.POST['username']
password = request.POST['password']
# Create a user object from authentication, or return None
user = authenticate(username=username, password=password)
# Check if user was created
if user is not None:
# Rest of the code, irrelevant...
from account.models import User as CustomUser
# Code snippit
def test_account_login_POST_successful_login(self):
# Create a user to test login
CustomUser.objects.create_user(
username='test_user',
email='test_user@intranet.com',
password='flibble'
)
response = self.client.post(self.login_url, {
'username': 'test_user',
'password': 'flibble'
})
self.assertEqual(response.status_code, 301)
class User(AbstractUser):
# Make the email field unique
email = models.EmailField(unique=True)
# Authentication
AUTH_USER_MODEL = 'account.User'