Upload Multiple Images to a Model with Django

Juli Colombo
Published in
5 min readAug 20, 2020

Get flexibility without having several image fields

Very often in projects, especially in ecommerces, the client wants to link an image to a product. Way too much time has passed by for me to learn that most of the time the requirement changes in the middle of the project: the client has to be able to upload more than one image to a merchandise. And not only that, the amount of images is variable depending on the product.

Sometimes the first reaction is to panic, but I’ve come to a solution that is pretty flexible and easy to implement. So if you are in the same situation, I beg you to stay calm and read this article, it may help you!

The problem

To associate an image to a model in Django, we need to define an ImageField in the corresponding model, setting some optional configurations:

from django.db import modelsclass MyModel(models.Model):
image = models.ImageField(upload_to='images/')

If we want to upload multiple images to a model this way, we just need to define as many fields as we need:

from django.db import modelsclass MyModel(models.Model):
image_one = models.ImageField(upload_to='images/')
image_two = models.ImageField(upload_to='images/')
image_three = models.ImageField(upload_to='images/')

This solution is fine if:

  • We know how many images we have
  • We need to access them by name, for instance: model.image_two

As we mentioned before, in ecommerces very often, we need a product gallery to show all the images referring to a product, and the amount of images and their names vary from one product to another, looking in the frontend something like this:

With the approach we made before, it’s unlikely that we can build a flexible design to reach the final goal.

The Image model

To be able to add several images to one product, we will need to have an intermediate…

Juli Colombo