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

时间:2020-02-08 12:14:23

标签: django unit-testing django-admin python-unittest

我尝试测试自定义操作。但是当我使用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/">

1 个答案:

答案 0 :(得分:2)

您无法使用self.user.password登录-这是用户的哈希值密码,而不是用户用于登录的密码-因此登录失败(您可以通过检查返回值login()来验证这一点-它将是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)