Skip to content

Commit 3a02b9e

Browse files
authored
docs about fix_request_files_middleware
1 parent 4a51ecf commit 3a02b9e

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

docs/docs/guides/input/file-params.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,3 +101,50 @@ def create_user(request, details: Form[UserDetails], avatar: File[UploadedFile]
101101
if avatar is not None:
102102
set_user_avatar(user)
103103
```
104+
105+
106+
107+
Sure! Here’s a Django Ninja documentation-style section for the described behavior and middleware solution:
108+
109+
110+
111+
## Handling request.FILES in PUT/PATCH Requests
112+
113+
**Problem**
114+
115+
```python
116+
@api.put("/upload") # !!!!
117+
def upload(request, file: File[UploadedFile]):
118+
...
119+
```
120+
121+
For some [historical reasosns Django’s](https://groups.google.com/g/django-users/c/BeBKj_6qNsc) `request.FILES` is populated only for POST requests by default. When using HTTP PUT or PATCH methods with file uploads (e.g., multipart/form-data), request.FILES will not contain uploaded files. This is a known Django behavior, not specific to Django Ninja.
122+
123+
As a result, views expecting files in PUT or PATCH requests may not behave correctly, since request.FILES will be empty.
124+
125+
**Solution**
126+
127+
Django Ninja provides a built-in middleware to automatically fix this behavior:
128+
`ninja.compatibility.files.fix_request_files_middleware`
129+
130+
This middleware will manually parse multipart/form-data for PUT and PATCH requests and populate request.FILES, making file uploads work as expected across all HTTP methods.
131+
132+
**Usage**
133+
134+
To enable the middleware, add the following to your Django settings:
135+
136+
```python
137+
MIDDLEWARE = [
138+
# ... your existing middleware ...
139+
"ninja.compatibility.files.fix_request_files_middleware",
140+
]
141+
```
142+
143+
**Auto-detection**
144+
145+
When Django Ninja detects a PUT or PATCH etc methods with multipart/form-data and expected FILES - it will throw an error message suggesting you install the compatibility middleware:
146+
147+
148+
Note: This middleware does not interfere with normal POST behavior or any other methods.
149+
150+

0 commit comments

Comments
 (0)