I have a form:
class MessageAttachmentForm(forms.ModelForm):
class Meta:
model = MessageAttachment
fields = ("attachment",)
And in my view, I have it receive some files with the incorrect names so I try to create a new MultiValueDict and submit the files one by one using the correct name like so:
if request.FILES:
files_dict = request.FILES.copy()
files_dict.clear()
for file in request.FILES:
files_dict["attachment"] = request.FILES.get(file)
attachment_form = MessageAttachmentForm(files_dict)
if attachment_form.is_valid():
attachment = attachment_form.save()
message_object.attachments.add(attachment)
Where origininally, the request.FILES
returns this:
<MultiValueDict: {'attachment0': [<InMemoryUploadedFile: some_image.png (image/png)>], 'attachment1': [<InMemoryUploadedFile: report.pdf (application/pdf)>]}>
And on every iteration of request.FILES
, when I add the file to the files_dict
, I get this:
<MultiValueDict: {'attachment': [<InMemoryUploadedFile: some_image.png (image/png)>]}>
#And
<MultiValueDict: {'attachment': [<InMemoryUploadedFile: report.pdf (application/pdf)>]}>
Which looks ok, but still doesn't work. I also tried using a regular dict but that was to no avail either.
The attachment_form.errors
says that the field attachment
is required.
Thank you for taking your time reading this any help is appreciated.