使用django.test.Client的补丁方法获取415代码

Mat*_*t D 8 python django

编辑:我已经尝试了这个问题中的所有内容,并没有解决问题.意思我尝试过我尝试在设置中手动将FormParser和MultiPartParser添加到DEFAULT_PARSER_CLASSES,我尝试将django.test.TestCase更改为rest_framework.test.APITestCase.我仍然得到相同的错误代码.

当我通过命令行向我的运行在localhost上的Django应用程序发送PATCH请求时,如下所示:

http -a <username>:<password> PATCH http://127.0.0.1:8000/post/1/ text="new text"
Run Code Online (Sandbox Code Playgroud)

它按预期工作,我得到200 OK代码.

当我尝试使用如下django.test.Client.patch方法在单元测试中执行相同的操作时:

In [1]: from django.test import Client
In [2]: client = Client()
In [3]: client.login(username='<username>', password='<password>')
Out[3]: True
In [4]: client.patch('/post/1/', {'text': 'new text'})
Out[4]: <Response status_code=415, "application/json">
Run Code Online (Sandbox Code Playgroud)

我收到415(不支持的媒体)响应代码.该response.dataISUnsupported media type "application/octet-stream" in request.'

如果我尝试添加参数content-type='application/json'patch方法(我不应该这样做,因为我能够发送GET,POST以及DELETE使用请求Client类没有提供参数)我得到一个400错误代码.而且response.data'JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)'

正如我所说的,当我使用类的get,deletepost方法,该行为是按预期.

我正确使用该方法吗?这是一个错误吗?

小智 14

据我所知,httpie发送一个内容类型的请求application/json.

所以,试试这个:

import json 
data = json.dumps({'text': 'new text'})

client.patch('/post/1/', data, content_type='application/json')
Run Code Online (Sandbox Code Playgroud)