使用Django管理员的一种表单上传多张图片

时间:2018-07-17 11:52:54

标签: python django

我想用一种形式上传多张图像,我认为我的问题在这里是我的观点

def home(request):
   if request.method == 'POST':
       form = DocumentForm(request.POST)
       files = DocumentForm(request.FILES.getlist('photo'))
       if form.is_valid():
            for f in files:
                 f.save() 
                 return render(request , 'core/home.html')
   else:
       form = DocumentForm()
   return render(request, 'core/home.html', {
       'form': form
   })

model.py:

class Document(models.Model):
    title = models.CharField(max_length = 150 )
    photo = models.FileField(upload_to= 'media')


    def __str__(self):
        return self.title

form.py:

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('title', 'photo', )
        widgets={"photo":forms.FileInput(attrs={'id':'files','required':True,'multiple':True})}

1 个答案:

答案 0 :(得分:0)

尝试更改此内容:

files = DocumentForm(request.FILES.getlist('photo'))

为此

files = request.FILES.getlist('photo')

然后

if form.is_valid():
    for f in files:
        file_form = DocumentForm(f) # some thing arround that 
        # Or just create it as Models Document.objects.create(...) or Document(...) and Document.save()
        file_Form.save() if file_Form.is_valid() else None            
        return self.form_valid(form)

https://docs.djangoproject.com/en/2.0/topics/http/file-uploads/#uploading-multiple-files