How to display images from product gallery

I have the Product Model, and under it, the ProductImages model.

I know how to create both, how to add those two forms together, how to upload images, and they do get uploaded to specified folder.

But on the single product template page, for the life of me, i can’t figure out how to display them.

I hope somebody can help.

Here are the models

# PRODUCT MODEL
class Product(models.Model):
    STATUS = (
        ('DRAFT', 'Draft'),
        ('PUBLISHED', 'Published'),
        ('DELETED', 'Deleted'),
        ('DISABLED', 'Disabled'),
        ('WAITING_APPROVAL', 'Waiting Approval'),
    )

    name = models.CharField(max_length=150, unique=True)
    slug = models.SlugField(max_length=160, unique=True)
    price = models.DecimalField(max_digits=7, decimal_places=2)
    description = models.TextField()
    short_text = models.CharField(max_length=150, blank=True, null=True,)
    featured_image = models.ImageField(upload_to=file_upload_path, default='default/demo.jpg')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    pid = ShortUUIDField(
        unique = True,
        length = 10,
        max_length = 13,
        alphabet = '0123456abcdefgh',
        prefix = 'pid',

    )
    status = models.CharField(max_length=20, choices=STATUS, default="published")
    in_stock = models.IntegerField(default=1)
    #in_stock = models.BooleanField(default=True)
    featured = models.BooleanField('See on homepage',default=False)
    #gallery = models.ImageField(upload_to='product-gallery/', default='default/demo.jpg')

    # RELATIONS
    category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, related_name='products')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='products')

    def __str__(self):
        return self.name
    
    def get_absolute_url(self):
        return reverse("shop:view_product", args=[str(self.slug)])
    
    def product_image(self):
        return mark_safe(f'<img src="{self.featured_image.url}" width="50" height="50" />')
    
    def clean(self):
        self.name = self.name.capitalize()
        self.slug = self.slug.lower()

    '''
    def get_discount_price(self):
        discount_ammount = (self.price * self.discount) / 100 
        price_with_discount = self.price - discount_ammount
        return price_with_discount
    '''

    class Meta:
        ordering = ('-created_at',)
    
class ProductImages(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_gallery')
    image = models.ImageField(upload_to='product-gallery/', blank=True, null=True)

Here is the views.py


# CREATE NEW PRODUCT
def add_product(request):
    form = ProductForm()
    gallery_form = ProductImagesForm()

    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        # add product gallery images
        files = request.FILES.getlist('image')
        if form.is_valid():
            product = form.save(commit=False)
            product.user = request.user
            name = request.POST['name']            
            #name = form.cleaned_data['name']
            product.slug = slugify(name)            
            product.save()

            # loop through images
            for i in files:
                ProductImages.objects.create(product=product, image=i)

            messages.success(request, f'Product {product} has beed created!')
            return redirect('dashboard:dashboard')
    
    context = {
        'form': form,
        'gallery_form': gallery_form
    }
    return render(request, 'shop/products/add.html', context)

Here is the template, i am trying to have a gallery displayed.


  {% for image in product_images %}
  {{image}}
  {% endfor %}
  
  <div class="_1260">
    <div class="product-gallery-2">
      {% for image in product_images %}
              <a href="#" class="lightbox-link w-inline-block w-lightbox">
                <img src="{{image.url}}" sizes="(max-width: 479px) 43vw, (max-width: 767px) 21vw, 23vw" srcset="images/4_1-p-500.jpg 500w, images/4_1.jpg 800w" alt="" class="image-4">
                <script type="application/json" class="w-json">{
          "items": [
            {
              "_id": "example_img",
              "origFileName": "4.jpg",
              "fileName": "4.jpg",
              "fileSize": 53023,
              "height": 800,
              "url": "{{image.url}}",
              "width": 800,
              "type": "image"
            }
          ],
          "group": "object-gallery"
        }
        </script>
              </a>

              {% endfor %}
              
      
    </div>
  </div>
  

And this is the result

It does see the objects, i just can’t understand why {{image.url}} is not working.

Thank you

Can you explain why <script></script> tag inside the for loop ???
this tag must be in the bottom of the template page OR in a separate file and then you can use ```{% include ‘path/to/script/file/js.html’ %}

Hi :slight_smile:
Okay so i have created the pages in Webflow.

I used their lightbox widget so for each lightbox item there is one script tag, as i can understand.

But i am open to any suggestion or advice on how to show image gallery for products, it does not have to be this from Webflow.

Thank you