M. Gar
M. Gar

Reputation: 887

Save multiple files using FileField

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?

Upvotes: 2

Views: 3567

Answers (2)

harmaahylje
harmaahylje

Reputation: 150

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)

Upvotes: 2

Kostas Livieratos
Kostas Livieratos

Reputation: 1067

Do something like this in the forms.py:

class FileFieldForm(forms.Form):
    attachment = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

Upvotes: 3

Related Questions