开发者

django form with multiple file fields

开发者 https://www.devze.com 2023-02-28 08:20 出处:网络
How do you handle multiple file fields in Django. For开发者_JAVA百科 example if I had only one form field i would pass the request.FILES[\'file\'] to a handling function. But what is the way to go whe

How do you handle multiple file fields in Django. For开发者_JAVA百科 example if I had only one form field i would pass the request.FILES['file'] to a handling function. But what is the way to go when there are more files?


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.


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.


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'})
0

精彩评论

暂无评论...
验证码 换一张
取 消