Django test - How to send a HTTP Post Multipart with JSON
django, http, post, python, testing
Solution
With `application/json` content-type, you cannot upload file.
Try following:
view:
def upload(request):
print request.FILES['file']
print json.loads(request.POST['json'])
return HttpResponse('OK')
test:
def test_upload_request(self):
with tempfile.NamedTemporaryFile() as f:
my_json = json.dumps({
"list": {
"name": "test name",
"description": "test description"
}
})
form = {
"file": f,
"json": my_json,
}
response = self.client.post(reverse('api:upload'),
data=form)
self.assertEqual(response.status_code, 200)
Problem
in my django tests, I want to send an HTTP Post Multipart which contains 2 parameters: - a JSON string - a file ``` def test_upload_request(self): temp_file = tempfile.NamedTemporaryFile(delete=False).name with open(temp_file) as f: file_form = { "file": f } my_json = json.dumps({ "list": { "name": "test name", "description": "test description" } }) response = self.client.post(reverse('api:upload'), my_json, content=file_form, content_type="application/json") os.remove(temp_file) def upload(request): print request.FILES['file'] print json.loads(request.body) ``` My code doesn't work. Any help ? If necessary, I can use an external python lib (I'm trying with requests) Thank you