6π
If you open the file first and then assign request.FILES to the open file object you can access your file.
request = self.factory.post('/')
with open(file, 'r') as f:
request.FILES['file'] = f
request.FILES['file'].read()
Now you can access request.FILES like you normally would. Remember that when you leave the open block request.FILES will be a closed file object.
3π
I made a few tweaks to @Einstein βs answer to get it to work for a test that saves the uploaded file in S3:
request = request_factory.post('/')
with open('my_absolute_file_path', 'rb') as f:
request.FILES['my_file_upload_form_field'] = f
request.FILES['my_file_upload_form_field'].read()
f.seek(0)
...
- Without opening the file as
'rb'
I was getting some unusual encoding errors with the file data - Without
f.seek(0)
the file that I uploaded to S3 was zero bytes
- Can't connect to server running inside docker container (Docker for mac)
- SSH into Django Shell
- Django ORM leaks connections when using ThreadPoolExecutor
- What cheat sheets exist for Django?
- Fabric + buildout as opposed to Fabric + pip + virtualenv
2π
You need to provide proper content type, proper file object before updating your FILES
.
from django.core.files.uploadedfile import File
# Let django know we are uploading files by stating content type
content_type = "multipart/form-data; boundary=------------------------1493314174182091246926147632"
request = self.factory.post('/', content_type=content_type)
# Create file object that contain both `size` and `name` attributes
my_file = File(open("/path/to/file", "rb"))
# Update FILES dictionary to include our new file
request.FILES.update({"field_name": my_file})
the boundary=------------------------1493314174182091246926147632
is part of the multipart form type. I copied it from a POST request done by my webbrowser.
- How to annotate Django view's methods?
- Is it possible to use a natural key for a GenericForeignKey in Django?
- Django: Limiting the number of relationships in a OnetoMany relationship
- Django β disable one of system checks
- ImportError: No module named bootstrap3
1π
All the previous answers didnβt work for me. This seems to be an alternative solution:
from django.core.files.uploadedfile import SimpleUploadedFile
with open(file, "rb") as f:
file_upload = SimpleUploadedFile("file", f.read(), content_type="text/html")
data = {
"file" : file_upload
}
request = request_factory.post("/api/whatever", data=data, format='multipart')
0π
Be sure that βfileβ is really the name of your file input field in your form.
I got that error when it was not (use name, not id_name)
- Django Haystack: filter query based on multiple items in a list.
- Why don't Django and CherryPy support HTTP verb-based dispatch natively?
- Django-Rest-Framework: Paginate nested object
- Serializer validate function is not called DRF