You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将现有Django单文件上传表单改造为支持多文件上传?

适配多文件上传的解决方案

Let's walk through modifying your existing code to support multi-file uploads—this should get you up and running quickly:

1. 更新表单(forms.py)

Django 3.0+ introduced the MultipleFileField which is designed specifically for multiple file uploads. If you're on a newer Django version, use this for cleaner built-in validation:

from django import forms

class DocumentForm(forms.Form):
    docfile = forms.MultipleFileField(
        label='Select files',
        help_text='max. 42 megabytes per file',
    )

If you're stuck on an older Django version (pre-3.0), you can modify the standard FileField to use a widget that allows multiple selections:

from django import forms

class DocumentForm(forms.Form):
    docfile = forms.FileField(
        label='Select files',
        help_text='max. 42 megabytes per file',
        widget=forms.ClearableFileInput(attrs={'multiple': True})
    )

2. 修改视图逻辑(views.py)

Your current view only handles a single file—we need to loop through all uploaded files and save each one as a separate Document instance:

from django.shortcuts import render, redirect
from django.urls import reverse
from .forms import DocumentForm
from .models import Document

def list(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            # Retrieve all uploaded files from the form submission
            uploaded_files = request.FILES.getlist('docfile')
            for file in uploaded_files:
                # Create and save a Document entry for each individual file
                newdoc = Document(docfile=file)
                newdoc.save()
            # Redirect to refresh the page with the updated document list
            return redirect(reverse('list'))
    else:
        form = DocumentForm()
    
    documents = Document.objects.all()
    return render(request, 'check/list.html', {'documents': documents, 'form': form})

Key changes here:

  • Use request.FILES.getlist('docfile') instead of request.FILES['docfile'] to grab all uploaded files (not just the first one)
  • Loop through each file and create a separate Document record for proper storage

3. 调整模板(list.html)

Good news—your existing template barely needs changes! If you used MultipleFileField or added the multiple attribute to the widget, the form field will automatically render an <input type="file" multiple> element. You can keep your original code as-is:

<form action="{% url 'list' %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <p>{{ form.non_field_errors }}</p>
    <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
    <p>
        {{ form.docfile.errors }}
        {{ form.docfile }}
    </p>
    <p><input type="submit" value="Upload" /></p>
</form>

额外注意事项

  • File Size Limits: Verify your Django settings have appropriate FILE_UPLOAD_MAX_MEMORY_SIZE and any custom MAX_UPLOAD_SIZE limits to handle multiple large files without errors.
  • Model Setup: Ensure your Document model's docfile field is configured correctly (usually models.FileField(upload_to='your/upload/path/')) to store files in the right location.
  • Validation (Older Django): If using the pre-3.0 widget approach, add custom validation to ensure at least one file is uploaded—since the default FileField doesn't enforce this for multiple selections.

内容的提问来源于stack exchange,提问作者Aaron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:52:32