0

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

Evan
  • 1,960
  • 4
  • 26
  • 54
  • Possible duplicate of [upload multiple files in django](https://stackoverflow.com/questions/39525188/upload-multiple-files-in-django) – Ayoub Benayache Sep 06 '19 at 00:33

1 Answers1

0

Use django `formsets. That should solve your problem and also take a look at this link for complete implementation.

iliya
  • 514
  • 6
  • 19
  • I didn't know much about formsets, but after a little reading, it seems like they allow multiple instances of a form on a page, is that true? I'm looking to upload multiple files through one form. – Evan Sep 06 '19 at 18:52
  • @Bird Did you check this [link](https://github.com/sigurdga/django-jquery-file-upload) in comments ? there is only one model to handle uploading images in one place – iliya Sep 06 '19 at 21:44