0

Previously my Django form had a field that supported uploading a single file:

image = forms.ImageField(required=False, help_text=_('Optional image (2.5 MB or less)'), allow_empty_file=True)

If the user tried to edit the form after submitting it, I displayed the previously uploaded file by binding it to the form like so:

if request.method == 'POST':
    ...
else:
    data = {'title': model.title}
    file = {'image': model.file}
    form = MyForm(data, file, instance=model)

To enable uploading multiple files, I've now changed the widget to:

image = forms.ImageField(required=False, help_text=_('Optional image (2.5 MB or less)'), allow_empty_file=True, widget=forms.ClearableFileInput(attrs={'multiple': True}))

This works fine when uploading the files, but I can't find a way to bind more than one file to the form when it comes to editing it.

Is there a solution using the current widget, or would it involve using a custom or multiple widgets?

Thanks.

alstr
  • 1,358
  • 18
  • 34

1 Answers1

0

This isn't possible with the standard widget.

A ClearableFileInput with multiple enabled provides access to the selected files via a MultiValueDict.

You can bind a MultiValueDict to an ImageField when initialising the form, but it will only ever bind the last image. This is because the widget extends FileInput, and its function value_from_datadict(self, data, files, name) returns files.get(name), rather than files.getlist(name).

So, in short, you have to come up with a custom solution. This answer helped me to see this.

alstr
  • 1,358
  • 18
  • 34