35👍
I’m late to the party, but I’ve been trying to figure this out for a while and finally have a solution.
Have a look at the code used here: https://code.djangoproject.com/ticket/12446
You can access multipart values with getlist. If my HTML form was:
<form enctype="multipart/form-data" action="" method="post">
<input type="file" name="myfiles" multiple>
<input type="submit" name="upload" value="Upload">
</form>
My django code to process it would look like:
for afile in request.FILES.getlist('myfiles'):
# do something with afile
Writing a form field/widget to handle this properly is my next step. I’m still rather new to using Django, so I’m learning as I go.
9👍
request.FILES.get('filename', None)
responds to the existence of a form-named field like this:
<input type="file" name="filename"></input>
If you had two such fields:
<input type="file" name="file1"></input>
<input type="file" name="file2"></input>
Then request.FILES.get('file1', None)
and request.FILES.get('file2', None)
should give you those files respectively.
The reason for this is multipart mime. The three parts (form data, file1, file2) should be uploaded and Django’s UploadFileHandler splits this apart into request.POST
and request.FILES
respectively.
- Getting file extension in Django template
- Django template img src not working
- Installed Virtualenv and activating virtualenv doesn't work
- Why is Django's Meta an old-style class?
- Is there any way to use GUIDs in django?
1👍
Here’s is a good link for this answer: https://github.com/Chive/django-multiupload. However, since I was not using ModelForm I had to make few changes.
In view I have written below code and saved files to disk:
for each in form.cleaned_data['attachments']:
handle_uploaded_file(each)
def uploadMyWork(request):
from .forms import UploadFileForm, handle_uploaded_file
print 'in uploadMyWork'
if request.method == 'GET':
print 'in uploadMyWork : GET'
form = UploadFileForm()
else:
form = UploadFileForm(request.POST, request.FILES)
print 'in uploadMyWork : POST'
#for each in form.cleaned_data['attachments']:
# handle_uploaded_file(each)
#return render(request, 'stitchme/uploadMyWork.html', {'msg': "file uploaded successfully"})
if form.is_valid():
print 'inside form valid'
for each in form.cleaned_data['attachments']:
handle_uploaded_file(each)
return render(request, 'stitchme/uploadMyWork.html', {'msg': "file uploaded successfully"})
print 'returning to uploadmywork'
return render(request, 'stitchme/uploadMyWork.html', {'form': form, 'msg':'hi'})