Is it possible to add files to request.FILES

I have a form that has an image select input and a text input, the latter expects a URL with an image.

I would like to upload both the image from the ImageField and the image from the URL.

I have got as far as completing various checks on the URL, and initialising a variable imgfile with the file data that has the type _io.BytesIO, and imgname that has the type str.

When I test what is in request.FILES (from the form’s ImageField) I see this:

print(type(self.request.FILES)
-> <class 'django.utils.datastructures.MultiValueDict'>

print(dict(self.request.FILES)
-> {'image_set-0-file': [<InMemoryUploadedFile: icons0.1.gif (image/gif)>]}

Then I add an element to self.request.FILES:

self.request.FILES['imgurl'] = InMemoryUploadedFile

print(dict(self.request.FILES)
-> {'image_set-0-file': [<InMemoryUploadedFile: icons0.1.gif (image/gif)>], 'imgurl': [<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>]}

So, at this point I am thinking that the imgurl dict element is not right, but I soldier on:

self.request.FILES['imgurl'].name = 'hello.png'

print(dict(self.request.FILES)
-> {'image_set-0-file': [<InMemoryUploadedFile: hello.png (image/gif)>], 'imgurl': [<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>]}

Now it’s obvious that this is not working, because self.request.FILES['image_set-0-file'].name has changed rather than self.request.FILES['imgurl'].name.

Is this just fundamentally the wrong technique, or have I made a minor (or major) coding error?

Thanks

Personally, I would try to avoid modifying request.FILES and instead supply the additional image to whatever is consuming request.FILES.

The first strategy was to write the file and the database reference directly. But I found that the roadblock there was that I didn’t have the foreign key necessary for the database write.

The second strategy was to try to understand how other files were uploaded/referenced and piggyback on that process. Which leads to trying to manipulate request.FILES. The problem here is laid out in my initial post.

So, I think it is probable that I need to dive down further into the code and, as you note, work out what request.FILES is being fed to. Initially I thought I’d run into a problem of getting my file data down to that process - but I think that wont necessarily be a problem, because my file data is derived from a field in request.DATA, which is presumably being managed somewhere down the line with request.FILES.

Probably your direction (the third way) will prove more fruitful. Thanks.