I'm trying to write an app that can handle uploading multiple files at a time. I had the app working for a single file upload, but adding a loop to process a list of files hasn't worked yet.
#models.py
class image(models.Model):
filename = models.CharField(max_length=100, blank=False, null=False)
image = models.ImageField(upload_to='images/')
uploaded_at = models.DateTimeField(auto_now_add=True)
user = models.CharField(max_length=100, default='default')
Form:
class ImageForm(forms.ModelForm):
class Meta:
model = image
fields = ('image',)
widgets = {'image': forms.ClearableFileInput(attrs={'multiple':True}),} # Added to allow multiple file selections in one dialog box
And relevant part of views.py
:
def image_upload(request):
if request.method == 'POST':
for f in request.FILES.getlist('image'):
formI = ImageForm(request.POST, f, instance=image())
if formI.is_valid():
fs = formI.save(commit=False)
fs.filename = f
fs.user = request.user
fs.save()
(There's other stuff going on in the view, but it currently breaks before that).
The result is the error:
AttributeError: 'TemporaryUploadedFile' object has no attribute 'get'
from the line: if formI.is_valid():
I originally had formI = ImageForm(request.POST, f, instance=image())
with request.FILES
instead of f
, and it seems likely that change is what's breaking this. What should I have instead of those two options? request.FILES
results in only one image out of the selected being uploaded.
What is the correct object to pass to ImageForm
?
Using Python 3.6.8 and Django 2.2.4
Edit: I've seen other SO questions about multiple file uploads, including the suggested duplicate, but none made clear to me what object ImageForm
needs (rather than f
in my example).