Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save multiple uploaded files in django

I want to upload and save multiple files in my application, I have
<input type="text" name="name" value="" />
<input type="file" name="file" multiple/>

in my template. when I hit upload, seems
form = MyForm(request.POST, request.FILES)
is only saving one file which is last in the list of the many uloaded files. How can I be able to save all the uploaded files using the form form = MyForm(request.POST, request.FILES) blah blah? Thanks

Edit
Myform is a model form from this model.

class Docs(models.Model):    
    name = models.CharField(max_length=128)
    file = models.FileField(max_length=100, upload_to="documents/")
like image 404
Alexxio Avatar asked Nov 23 '13 13:11

Alexxio


People also ask

Does Python Django support multiple file upload?

Here is a quick example of how to add a multiple file form to your Django application. Most multiple-upload front-ends were created without Django in mind, so interfacing with tools is not always straightforward as it might be with a different language.


2 Answers

You maybe use request.FILES['file'] or request.FILE.get('file') in MyFOrm. They only return a file.

Use request.FILE.getlist('file') to get multiple files.


In your view:

....
form = MyForm(request.POST, request.FILES)
if form.is_valid():
    name = form.cleaned_data['name']
    for f in request.FILES.getlist('file'):
        Docs.objects.create(name=name, file=f)
    return HttpResponse('OK')
...
like image 78
falsetru Avatar answered Sep 20 '22 14:09

falsetru


The answer of @faksetru does not include save() method. So if you want to save your instace, it looks like this:

# in views.py
from .models import Docs
...
form = MyForm(request.POST, request.FILES)
if form.is_valid():
    name = form.cleaned_data['name']
    for f in request.FILES.getlist('file'):
        instance = Docs(name=name, file=f)
        instance.save()
    return HttpResponse('OK')

For the more details refer to official documentation of Django.

UPDATE:

I wrote a full answer here, please check it out.

like image 37
karjaubayev Avatar answered Sep 21 '22 14:09

karjaubayev