Skip to content
thesarfo

Note

Adding Images to Products

A ProductImage model with a one-to-many relationship to Product, using ImageField and Pillow.

views 0

So now, we want a product to have 2 or more images associated to it. So we want to add Images to a product. So we have to build the product image model.- There will be a one to many relationship between products and images. see below

class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images')
image = models.ImageField(upload_to='store/images') #note that we use an imagefield for this

Note that the upload to is relative to the MEDIA_ROOT in the settings.py file, so since we set the root to the ‘media’ folder, Product Images will be stored in media/store/images.

Now the next thing we do is to install Pillow for handling images with ‘pip install pillow’. Now makemigrations and apply the migrations.