[Solved]-Django RequestFactory file upload

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.

πŸ‘€Einstein

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

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.

πŸ‘€Ramast

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')
πŸ‘€Chris Maes

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)

Leave a comment