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)