为什么我不能使用客户端登录到管理员?

Why I can't login to admin using client?

我尝试测试我的自定义操作。但是当我使用 client 进入管理页面时,出现错误 <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/admin/login/?next=/admin/donation/donation/">

class ExportToExcelTestCase(TestCase):
    def setUp(self) -> None:
        self.user = UserFactory()

    def test_export_to_excel(self) -> None:
        data = {'action': 'export_to_excel'}
        change_url = '/admin/donation/donation/'
        self.user.is_staff = True
        self.user.is_superuser = True
        self.user.save()
        self.client.login(username=self.user.username, password=self.user.password)
        response = self.client.post(change_url, data)
        print(response)   #<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/admin/login/?next=/admin/donation/donation/">

您无法使用 self.user.password 登录 - 这是用户的 散列 密码,而不是他们用于登录的密码 - 因此您的登录失败(您可以通过检查 login() 的 return 值来验证这一点 - 它将是 False)。

由于您实际上并未在此处测试身份验证,因此您应该改用 force_login

def test_export_to_excel(self) -> None:
    data = {'action': 'export_to_excel'}
    change_url = '/admin/donation/donation/'
    self.user.is_staff = True
    self.user.is_superuser = True
    self.user.save()
    self.client.force_login(self.user)
    response = self.client.post(change_url, data)