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

Django中同时提交表单与上传文件报错:未选择文件

解决Django表单文件上传提示“未选择文件”的问题

你遇到的核心问题是表单提交时文件未被正确传递到后端,导致字段验证失败,以下是具体修复步骤和修改后的代码:

关键错误点及修复方向

  • 表单缺少文件上传必需编码:HTML表单必须添加enctype="multipart/form-data"属性,否则浏览器不会发送文件数据到服务器。
  • 视图表单实例逻辑混乱:重复创建表单对象且未将request.FILES传入验证实例,导致文件字段验证不通过。
  • 文件存储路径不规范(可选优化):硬编码路径易出错,建议用Django配置的MEDIA_ROOT管理上传目录。

修改后的代码

1. index.html(添加enctype属性)

<head>
    <meta charset="UTF-8">
    <title>User Information Form</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="Submit" name="submit" value="Submit"/>
</form>

{% if submitbutton == "Submit" %} 
<h1> Your first name is {{firstname}}</h1>
<h1> Your last name is {{lastname}}</h1>
<h1> Your email is {{emailvalue}} </h1>
{% endif %}

</body>
<script>'undefined'=== typeof _trfq || (window._trfq = []);'undefined'=== typeof _trfd && (window._trfd=[]),_trfd.push({'tccl.baseHost':'secureserver.net'},{'ap':'cpbh-mt'},{'server':'p3plmcpnl487010'},{'dcenter':'p3'},{'cp_id':'8437534'}) // Monitoring performance to make your website faster. If you want to opt-out, please contact web hosting support.</script><script src='https://img1.wsimg.com/traffic-assets/js/tccl.min.js'></script></html>

2. views.py(简化表单实例逻辑,正确传入文件数据)

from django.shortcuts import render
from .forms import UserForm
from mysite.functions import handle_uploaded_file

def index(request):
    submitbutton = request.POST.get("submit")
    firstname = ''
    lastname = ''
    emailvalue = ''

    # 仅创建一个表单实例,同时传入POST和FILES数据
    form = UserForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        firstname = form.cleaned_data.get("first_name")
        lastname = form.cleaned_data.get("last_name")
        emailvalue = form.cleaned_data.get("email")
        # 从表单cleaned_data中获取文件,更安全
        handle_uploaded_file(form.cleaned_data['file'])

    context = {
        'form': form, 
        'firstname': firstname, 
        'lastname': lastname,
        'submitbutton': submitbutton, 
        'emailvalue': emailvalue
    }
    
    return render(request, 'index.html', context)

3. functions.py(优化路径,确保目录存在)

import os
from django.conf import settings

def handle_uploaded_file(f):  
    # 基于MEDIA_ROOT构建上传路径,自动创建目录
    upload_dir = os.path.join(settings.MEDIA_ROOT, 'upload')
    os.makedirs(upload_dir, exist_ok=True)
    file_path = os.path.join(upload_dir, f.name)
    
    with open(file_path, 'wb+') as destination:  
        for chunk in f.chunks():  
            destination.write(chunk)

4. 可选配置(settings.py添加MEDIA参数)

在项目settings.py中添加以下内容,规范文件上传根目录:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

验证修复效果

  1. 重启Django开发服务器
  2. 访问表单页面,填写信息并选择文件提交
  3. 文件将保存到指定目录,表单数据可正常获取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:40:41