0

Is there any way to upload multiple photos, with the same upload button? I know there is an extra widget that you can add a certain amount of images to a modelformset_factory, but I am looking for a way to let the user decide how many photos to upload. Everything works fine if I add extra=3 to the formset. But I would like to eliminate that altogether. Some users will want to upload 3 pics, some will want to upload maybe 25.

My view

def list_home(request):
    image_form_set = modelformset_factory(Images, form=ImageForm)
    if request.method == "POST":
        listing_form = ListingForm(request.POST)
        formset = image_form_set(request.POST, request.FILES, queryset=Images.objects.none())
        if listing_form.is_valid() and formset.is_valid():
            post = listing_form.save(commit=False)
            post.user = request.user
            post.save()
            for form in formset.cleaned_data:
                if form:
                    image = form['image']
                    photo = Images(listing=post, image=image)
                    photo.save()
                    return render(request, 'success.html')

My Form

class ListingForm(forms.ModelForm):

class Meta:
    model = Listing
    exclude = ('user', 'longitude', 'latitude', 'pub_date')


class ImageForm(forms.ModelForm):
    image = forms.ImageField(label='Image', widget=ClearableFileInput(attrs={'multiple': True}))

    class Meta:
        model = Images
        fields = ['image']

My Image model

class Images(models.Model):
    image = models.ImageField(upload_to=get_image_filename, verbose_name='Image')
    listing = models.ForeignKey(Listing, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.image)
master_j02
  • 377
  • 3
  • 13

1 Answers1

0

Why do you not upload multiple files in one form:

<form action="/pic_upload/" method="post" enctype="multipart/form-data"> 
{% csrf_token %} 
 <table>
  <tr>
   <td>select file to upload: </td><td><input name="files" type="file" size="50" accept="image/*" multiple>  </td><td>
   <button type="submit"> Upload </button> </td>
  </tr>
 </table>
</form>

The view function then should look something like:

def pic_upload(request):

    for afile in request.FILES.getlist('files'):
        if afile.content_type not in ("image/png","image/jpeg"):
            continue
        pic = Images()
        pic.image= afile
        pic.save()

    return redirect(......)
ger.s.brett
  • 3,267
  • 2
  • 24
  • 30