Search code examples
python-3.xdjangoe-commerce

Beginner problem. How i can display all images from a product? Django + Python


I'm a beginner and i need a little help. I want to display all images from a product and i can't find the right way.

the code is below:

models.py:

class Product(models.Model):
   name = models.CharField(max_length=200)
   short_description = models.CharField(
    max_length=200, null=True, blank=True, help_text="Enter a brief description of the product")
   description = models.TextField(blank=True, null=True)
   price = models.DecimalField(max_digits=7, decimal_places=2)
   digital = models.BooleanField(default=False, null=True, blank=True)
   default_image = models.ImageField(null=True, blank=True)


 def __str__(self):
    return self.name

 def get_absolute_url(self):
    return reverse('product-detail', args=[str(self.id)])

 @property
def imageURL(self):
    try:
        url = self.default_image.url
    except:
        url = ''
    return url


 def image_tag(self):
    return mark_safe('<img src="{}" height="50"/>'.format(self.default_image.url))

image_tag.short_description = 'Image'




  class ProductImage(models.Model):
product = models.ForeignKey(
    Product, on_delete=models.CASCADE, default=None, related_name='images')
title = models.CharField(max_length=50, null=True, blank=True)
image = models.ImageField(null=True, blank=True)

def __str__(self):
    return self.product.name

this is the view:

class ProductDetail(DetailView):
model = Product

URL:

path('product/<int:pk>', views.ProductDetail.as_view(), name='product-detail'),

and template product_detail.html:

{% extends 'store/home.html' %}
{% load static %}
{% block content %}
<div>
    <h1>{{ product.name }}</h1>
    <p>{{ product.description }}</p>
    <!--<img src="{{product.imageURL}}" alt=""> -->

    </div>
    {% endblock %}

The comment is returning only the default image. The indentation is correct in my VS Code but here is pretty hard to write it. Any suggestions would be greatly appreciated. Thank you.


Solution

  • Try:

    {% for product_image in product.images.all %}
        <img src="{{ product_image.image.url }}" alt="{{ product_image.title }}">
    {% endfor %}
    

    in place of the commented-out <img src="{{product.imageURL}}" alt="">. The key here is the use of product.images.all. I recommend you read about the Django ORM's reverse relations feature.