Skip to content

[BUG] JSON payload not parsed when using upload with extra fields #1306

Open
@matt0x6F

Description

@matt0x6F

Describe the bug
Ninja fails to parse the request body correctly and throws a validation error, contrary to the instructions under Upload files with extra fields.

Versions (please complete the following information):

  • Python version: 3.11.7
  • Django version: 5.1.1
  • Django-Ninja version: 1.3.0
  • Pydantic version: 2.9.2

Relevant schema

class FileMetadata(Schema):
    posts: List[int] = []
    visibility: str = "public"

API Code

@files_router.post(
    "/", response={200: FileDetails}, tags=["files"], auth=JWTAuth(permissions=StaffOnly)
)
def create_file(request: HttpRequest, metadata: FileMetadata, upload: NinjaFile[UploadedFile]):
    """
    Creates a file with or without post associations.
    """
    try:
        if metadata.visibility == "public":
            stored_name = PublicStorage().save(upload.name, upload.file)

            url = PublicStorage().url(stored_name)
        else:
            stored_name = PrivateStorage().save(upload.name, upload.file)

            url = PrivateStorage().url(stored_name)

        upload = File.objects.create(
            location=url,
            name=stored_name,
            content_type=upload.content_type,
            charset=upload.charset,
            size=upload.size,
            visibility=metadata.visibility,
        )

        if metadata:
            upload.posts.set(metadata.posts)

        return upload
    except Exception as err:
        logger.error("Error creating file", error=err)

        raise HttpError(500, "Fail to create file") from err

Request body

-----------------------------291645760626718691221248293984
Content-Disposition: form-data; name="upload"; filename="business card front.pdf"
Content-Type: application/pdf

file stuff
%%EOF

-----------------------------291645760626718691221248293984
Content-Disposition: form-data; name="metadata"; filename="blob"
Content-Type: application/json

{"posts":[2,4],"visibility":"public"}
-----------------------------291645760626718691221248293984--

Content-Type on the request is set to multipart/form-data; boundary=---------------------------291645760626718691221248293984

Response

{
	"detail": [
		{
			"type": "missing",
			"loc": [
				"body",
				"metadata"
			],
			"msg": "Field required"
		}
	]
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions