Search code examples
pythonhtmldjangodjango-modelsdjango-views

Upload multiple photos for a product in the store


I am loading a store site with Django. I need to upload 4 photos for one product But I can only upload one photo can you help me?

my models in products:

class Product(models.Model):
    Name = models.CharField(max_length=60)
    Descriptions = models.TextField()
    Price = models.IntegerField()
    Image = models.ImageField(upload_to='product')
    category = models.ManyToManyField(Category, null=True, blank=True)
    Discount = models.SmallIntegerField(null=True, blank=True)
    Size = models.ManyToManyField(ProductSize, related_name='product')
    Color = models.ManyToManyField(ProductColor, related_name='product', blank=True)
    Property = models.ManyToManyField(ProductProperty, related_name='product')

My Views in products:

class ProductDetail(DetailView):
    template_name = 'product/single-product.html'
    model = Product

Solution

  • Option - 1: Use ForeignKey to upload multiple images

    class Images(models.Model):
        post = models.ForeignKey(Product, default=None)
        image = models.ImageField(upload_to=get_image_filename,
                                  verbose_name='Image')
    

    Option - 2: without image field

    This is the preferred way - I have applied this in my project

    1. Add image at a specific location (at filesystem or AWS S3)
    2. Like: prod_images/product_id/image1.jpg, prod_images/product_id/image2.jpg ...
    3. In your views you can respond back with above images links