Okay so I've looked at many of the answers on the internet but none seem to solve this problem. I'm trying to save each from a multifile upload but it keeps saving the same file f number of times. Something with my 'form' attribute is causing this problem but i can't seem to figure out why.

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 Answers

0
Community On Best Solutions

Managed to solve my problem by creating an instance of BookForm and submitting the data through the loop. Hope this helps somebody else in the future.

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
})