我的模板html具有以下输入(多个):
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input name="image_field" type="file">
<input name="image_field" type="file">
我的观点是:
def add_listing(request):
if request.method == 'POST':
image_form = ImageForm(request.FILES)
files = request.FILES.getlist('image_field')
if image_form.is_valid():
if object = Object.create() # since all images should relate to this object e.g. this object is the foreign key
for f in files: # add images
Image.objects.create(pk=None, object=object, image=f)
object.save()
return render(request, 'dashboard/add_listing.html', {'image_form': image_form})
Forms.py
class ImageForm(forms.ModelForm):
image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
class Meta:
model = ListingImage
fields = ['image', ]
一些调试输出:
(Pdb) image_form.is_valid()
False
(Pdb) files
[<InMemoryUploadedFile: WhatsApp Image 2018-04-08 at 20.11.17.jpeg (image/jpeg)>]
(Pdb)
我的目标是处理可以使用相同名称的n
输入的表单,并为输入中的每个文件验证它并创建一个对象。
答案 0 :(得分:0)
我需要替换image_form = ImageForm(request.FILES)
与
image_form = ImageForm(request.POST, request.FILES)
。
我不确定为什么这是必需的,因为listing_form
只包含文件字段,任何解释都会受到赞赏!