Hi3e
Hi3e

Reputation: 75

Upload multiple images at once django

How can I submit 3 images at once with a single input.

class Image(models.Model):
imageuploader_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True)
image = models.FileField(upload_to ='pictsagram/') 

Upvotes: 1

Views: 4476

Answers (2)

Chris
Chris

Reputation: 2212

I do not think this is too complicated. You just need a form with a file input having the multiple attribute and then save all the files in your view.

E.g. a very basic example

#forms.py

class ImageForm(forms.Form):

    images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

Your html form

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
    <button type="submit">Upload</button>
</form>

And then create your images in your view, using getlist on the field

    # views.py
    def images_upload(request):

        if request.method == 'POST':
            form = ImageForm(request.POST, request.FILES)
            if form.is_valid():
                for img in request.FILES.getlist('images'):
                    Image.objects.create(imageuploader_profile=request.user, image=img)
                return redirect('images_upload')

        form = ImageForm()

        context = {'form': form}

        return render(request, 'images.html', context)

Upvotes: 3

Micheal J. Roberts
Micheal J. Roberts

Reputation: 4170

So, I think this is an instance of where you need to make use of the ManyToMany relationship field, creating a new model instance which stores one image, e.g., (and this is a simplistic version of something like what you would need).

from django.db import models

class ImageAttachment(models.Model):
    file = models.FileField(upload_to ='pictsagram/')

Then, in your Image model:

class Image(models.Model):
    imageuploader_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True)
    images = models.ManyToManyField(ImageAttachment)

The user will then pass up X number of images to the server, at which point you will create multiple images, and append them to the images field for the Image model.

As code organisation goes, I would also consider renaming you Image model, as it is actually storing multiple images ...

Upvotes: 0

Related Questions