diff --git a/ninja/params/models.py b/ninja/params/models.py index 7a70e938d..d048a861c 100644 --- a/ninja/params/models.py +++ b/ninja/params/models.py @@ -183,7 +183,11 @@ def get_request_data( for name, annotation in cls.__ninja_body_params__.items(): if name in request.POST: data = request.POST[name] - if annotation is str and data[0] != '"' and data[-1] != '"': + if ( + annotation is str + and not data.startswith('"') + and not data.endswith('"') + ): data = f'"{data}"' req.body = data.encode() results[name] = get_request_data(req, api, path_params) diff --git a/tests/test_forms_and_files.py b/tests/test_forms_and_files.py index f42c4f796..6e8e895e4 100644 --- a/tests/test_forms_and_files.py +++ b/tests/test_forms_and_files.py @@ -1,6 +1,6 @@ from django.core.files.uploadedfile import SimpleUploadedFile -from ninja import File, Form, NinjaAPI, UploadedFile +from ninja import Body, File, Form, NinjaAPI, UploadedFile from ninja.testing import TestClient api = NinjaAPI() @@ -16,6 +16,15 @@ def str_and_file( return {"title": title, "data": file.read().decode()} +@api.post("/str_body_and_file") +def str_body_and_file( + request, + title: str = Body(...), + file: UploadedFile = File(...), +): + return {"title": title, "data": file.read().decode()} + + client = TestClient(api) @@ -57,3 +66,14 @@ def test_files(): }, "required": True, } + + +def test_empty_multipart_body_field(): + file = SimpleUploadedFile("test.txt", b"data123") + response = client.post( + "/str_body_and_file", + FILES={"file": file}, + POST={"title": ""}, + ) + assert response.status_code == 200 + assert response.json() == {"title": "", "data": "data123"}