save multiple uploaded files in django

人盡茶涼 提交于 2019-12-05 03:54:19

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')
...

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!