2

In a existing form I use a FileField to attach differents type of files .txt, .pdf, .png, .jpg, etc and work fine but now I need that field to accept several files, so I use the propertie multiple for the input to accept more of one files but when is stored in my database only stored the path for the first selected file and in the media folder are only stored one file no the others, this is what I have:

forms.py
class MyForm(forms.Form):
    attachment = forms.FileField(required=False,widget=forms.ClearableFileInput(attrs={'multiple': True}))

models.py
class MyFormModel(models.Model):
    attachment = models.FileField(upload_to='path/', blank=True)

Is posible to store in the DB all the paths separete in this way path/file1.txt,path/file2.jpg,path/file3.pdf and store the three files in the media folder? Do I need a custom FileField to procces this or the view is where I need to handle this?

EDIT: The answer @harmaahylje gives me comes in the docs but not for the versión I use 1.8 this affect the solution?

M. Gar
  • 889
  • 4
  • 16
  • 33

2 Answers2

3

Do something like this in the forms.py:

class FileFieldForm(forms.Form):
    attachment = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
Kostas Livieratos
  • 965
  • 14
  • 33
  • That allows me a multi select input but in the DB just store the path for one of the multiple files and also one file in my media folder. – M. Gar Aug 15 '17 at 19:06
  • You are right. The actual solution to the problem is my answer combined with @harmaahylje's answer below – Kostas Livieratos Aug 15 '17 at 22:19
2

Django docs have the solution https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#uploading-multiple-files

In your view:

def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        files = request.FILES.getlist('file_field')
        if form.is_valid():
            for f in files:
                ...  # Do something with each file.
            return self.form_valid(form)
        else:
            return self.form_invalid(form)
harmaahylje
  • 150
  • 1
  • 6
  • well in the `# Do something with each file.` part I try to assign the f file in the attachment field but still sabe just one path, there is where I miss what to do. – M. Gar Aug 15 '17 at 22:44
  • @M.Gar You will need to create a new object for each file. `MyFormModel.objects.create(attachment=f)` – harmaahylje Aug 16 '17 at 08:03
  • That gives me this error `Manager isn't accessible via MyFormModel instances`. – M. Gar Aug 16 '17 at 16:42
  • I try with the model and not the instance and now gives me this error `save() got an unexpected keyword argument 'force_insert'`. – M. Gar Aug 16 '17 at 17:00
  • @M.Gar Please post some code, what are you trying to do. – harmaahylje Aug 16 '17 at 18:49
  • I found it easier to create another model just for files and make an relation between the two – Papis Sahine Nov 10 '21 at 17:46