好的,所以我看了互联网上的许多答案,但似乎没有一个能解决这个问题。我正在尝试从多文件上传中保存每个文件,但它会多次保存同一文件。带有“ form”属性的东西导致了此问题,但我似乎无法弄清楚原因。
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
})
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ('pdf',)
widgets = {
'pdf': forms.ClearableFileInput(attrs={'multiple': True}),
}
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)
答案 0 :(得分:0)
设法通过创建BookForm实例并通过循环提交数据来解决我的问题。希望将来对其他人有帮助。
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
})