如何在django中设置request.body请求工厂发布请求?

时间:2016-06-13 21:33:00

标签: python django unit-testing

尝试在python单元测试中设置request.body为

        self.factory = RequestFactory()
        self.request = self.factory.get(reverse('get_associations'))
        self.request.user = self.auth_user
        self.request.body = json.dumps(self.post_data)

但它给出了错误:

self.request.body = json.dumps(self.post_data)
AttributeError: can't set attribute

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:10)

根据this answer,试试这个:

self.request = self.factory.get(reverse('get_associations'),
                                data=json.dumps(self.post_data),
                                content_type='application/json')