如何在Django中使用for循环将每个文件保存在request.FILES中?

时间:2019-04-19 02:05:47

标签: python django

好的,所以我看了互联网上的许多答案,但似乎没有一个能解决这个问题。我正在尝试从多文件上传中保存每个文件,但它会多次保存同一文件。带有“ form”属性的东西导致了此问题,但我似乎无法弄清楚原因。

views.py

def upload_book(request):
if request.method == 'POST':  
    for f in request.FILES.getlist('pdf'):
        form = BookForm()
        form = BookForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
    return redirect('book_list')
else:
    form = BookForm()
return render(request, 'upload_book.html', {
    'form': form
})

forms.py

    class BookForm(forms.ModelForm):
        class Meta:
            model = Book
            fields = ('pdf',)
            widgets = {
                'pdf': forms.ClearableFileInput(attrs={'multiple': True}),
            }

models.py

    class Book(models.Model):
        pdf = models.FileField(upload_to='books/pdfs/')

        def __str__(self):
            return self.title

        def delete(self, *args, **kwargs):
            self.pdf.delete()
            super().delete(*args, **kwargs)

1 个答案:

答案 0 :(得分:0)

设法通过创建BookForm实例并通过循环提交数据来解决我的问题。希望将来对其他人有帮助。

Views.py

    def upload_book(request):
if request.method == 'POST':
    for f in request.FILES.getlist('pdf'):
        form = BookForm(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.pdf = f
            obj.save()
    return redirect('book_list')
else:
    form = BookForm()
return render(request, 'upload_book.html', {
    'form': form
})