Django:具有多个输入的表单无效

时间:2018-04-23 13:47:20

标签: python django django-forms django-views

我的模板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输入的表单,并为输入中的每个文件验证它并创建一个对象。

1 个答案:

答案 0 :(得分:0)

我需要替换image_form = ImageForm(request.FILES)

image_form = ImageForm(request.POST, request.FILES)

我不确定为什么这是必需的,因为listing_form只包含文件字段,任何解释都会受到赞赏!