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

Django文件上传功能异常:文件无法成功上传求助

Django多文件上传失败问题解决

问题概述

提交上传表单后无文件被保存到配置好的MEDIA_ROOT目录,请求日志显示跳转正常,但文件未实际上传。

错误点分析及修正

1. 表单字段未启用多文件支持

原表单仅在组件层面设置了multiple=True,但表单字段本身未开启多文件接收逻辑,导致无法正确处理多个上传文件。

修正后表单代码:

from django import forms

class UploadDocumentForm(forms.Form):
    # 添加multiple=True参数,明确支持多文件上传
    files = forms.FileField(widget=forms.FileInput(attrs={'multiple': True}), label='', multiple=True)

2. 视图中文件列表获取方式错误

原代码直接遍历self.request.FILES,得到的是字段名称而非实际文件对象,无法生成有效的模型实例。

修正后视图代码:

from django.urls import reverse_lazy
from django.views.generic import FormView
from .models import Document

class UploadDocumentView(FormView):
    template_name = 'upload-document.html'
    form_class = UploadDocumentForm
    success_url = reverse_lazy('upload-document')

    def form_valid(self, form):
        # 通过字段名获取所有上传的文件列表
        uploaded_files = self.request.FILES.getlist('files')
        Document.objects.bulk_create([Document(file=f) for f in uploaded_files])
        return super().form_valid(form)

3. 模型FileField配置错误

原模型未设置合理的upload_to路径,直接使用settings.MEDIA_ROOT会导致路径拼接异常,无法正确存储文件。

修正后模型代码:

from django.db import models

class Document(models.Model):
    # 使用相对路径,文件将自动保存到MEDIA_ROOT/documents/目录
    file = models.FileField(upload_to='documents/')

额外配置检查

确保settings.py中媒体文件配置正确:

MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'

开发环境下,需在项目根urls.py添加媒体文件路由:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # 你的其他路由配置
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

内容的提问来源于stack exchange,提问作者watch-this

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:35:26