这个问题通常是由于文件表单字段没有正确设置为multipart/form-data引起的。以下是一个示例表单集和视图函数,可以将它们作为参考来解决上传图片时遇到的问题:
forms.py:
from django import forms
class ImageUploadForm(forms.Form):
picture = forms.ImageField()
views.py:
from django.forms import formset_factory
from django.http import HttpResponse
from django.shortcuts import render
from .forms import ImageUploadForm
def multiple_image_upload(request):
ImageUploadFormSet = formset_factory(ImageUploadForm, extra=3)
if request.method == 'POST':
formset = ImageUploadFormSet(request.POST, request.FILES)
if formset.is_valid():
for form in formset:
picture = form.cleaned_data.get('picture')
# 处理上传的图片
return HttpResponse('图片上传成功!')
else:
formset = ImageUploadFormSet()
return render(request, 'multiple_image_upload.html', {'formset': formset})
在模板文件中,确保在表单标签中添加enctype="multipart/form-data"属性,如下所示:
{% extends 'base.html' %}
{% block content %}
{% endblock %}
上一篇:表单计算失败