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

Django中使用enctype='multipart/form-data'无法存储图片求助

Django图片上传失败问题解决方法

问题现象

表单使用enctype='multipart/form-data'时图片无法存储,不使用该属性仅能保存图片名称,文本数据可正常存入数据库。

修复步骤

1. 修正视图中文件获取逻辑(views.py)

上传的文件对象不在request.POST中,而是在request.FILES集合里,需修改获取方式:

def index(request):
    if request.method == "POST":
        dish_name = request.POST.get('dish_name')
        dish_size = request.POST.get('dish_size')
        dish_price = request.POST.get('dish_price')
        dish_description = request.POST.get('dish_description')
        # 从request.FILES中获取上传的图片文件
        dish_image = request.FILES.get('dish_image')
        dish_category = request.POST.get('dish_category')
        
        # 构造对象参数,兼容未上传图片的情况
        item_params = {
            'dish_name': dish_name,
            'dish_size': dish_size,
            'dish_price': dish_price,
            'dish_description': dish_description,
            'dish_category': dish_category,
            'dish_date': datetime.today()
        }
        if dish_image:
            item_params['dish_image'] = dish_image
            
        item = dish(**item_params)
        item.save()
        
    dishs = dish.objects.all()
    params = {'dish': dishs}
    return render(request, "card/index.html", params)

2. 修正模型主键字段(models.py)

AutoField需要实例化并指定为主键,否则会导致模型映射异常:

class dish(models.Model):
    dish_id = models.AutoField(primary_key=True)  # 补充实例化语法与主键设置
    dish_name = models.CharField(max_length=255, blank=True, null=True)
    dish_category = models.CharField(max_length=255, blank=True, null=True)
    dish_size = models.CharField(max_length=7, blank=True, null=True)
    dish_price = models.IntegerField(blank=True, null=True)
    dish_description = models.CharField(max_length=255, blank=True, null=True)
    # upload_to为MEDIA_ROOT下的子目录,无需重复写media
    dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True)
    dish_date = models.DateField()

    def __str__(self):
        return self.dish_name

3. 优化URL配置(urls.py)

Django的path不需要开头的斜杠,同时清理重复路径:

urlpatterns = [
    path('', views.index),
    path('index/', views.index),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

4. 安装图片处理依赖

Django处理ImageField需要依赖Pillow库,确保已安装:

pip install pillow

验证要点

  • 表单必须保留enctype='multipart/form-data',这是文件上传的必要条件。
  • 上传成功后,检查项目根目录下的media/images/文件夹,确认图片文件已生成;数据库中dish_image字段会存储图片的相对路径(如images/xxx.jpg)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:31:01