在使用Django REST framework
的时候,如果你在测试PUT/PATCH
请求时,遇到以下错误:
rest_framework.exceptions.UnsupportedMediaType: Unsupported media type "application/octet-stream" in request.
那么意为着你的请求是以application/octet-stream
方式发送的,这也是Django
的默认发送方式。
如果我们用的是self.client.put
或self.client.patch
,即我们使用的是Django
自带的TestCase
进行测试,那么我们需要在请求时将content_type
设置为application/json
:
response = self.client.patch(reverse('resouces.single'), data={'name': 'Eagle'}, content_type='application/json')
或者,我们可以使用Django REST framework
为我们准备的APITestCase
:
from rest_framework.test import APITestCase
class MyTest(APITestCase):
def test_patch_request_succeeds():
response = self.client.patch(reverse('resouces.single'), data={'name': 'Eagle'})
可以看到,我们不需要再特别注明content_type
为application/json
,因为APITestCase
已经帮我们处理好了。
想更多地了解APITestCase
,请查看
http://www.django-rest-framework.org/api-guide/testing/#api-test-cases