Hello Django Community,
I am trying to display a list of active products on page along with a primary image that is assigned to each product. Each product can have more than 1 image/photo but I only want the one designated as primary to show up on the index page along with the product description. All the product information is correctly displayed but I cannot get the data associated with the second model (ProductImage) ie image caption and image field to show up in the template. Any advice would be appreciated. Thanks again.
Marc
MODELS
class Product(models.Model):
name = models.CharField(max_length=200)
wood_species = models.ForeignKey(WoodSpecies, on_delete=models.PROTECT)
product_type = models.ForeignKey(ProductType, on_delete=models.PROTECT)
width = models.DecimalField(max_digits=4, decimal_places=2)
length = models.DecimalField(max_digits=4, decimal_places=2)
height = models.DecimalField(max_digits=4, decimal_places=2)
price = models.DecimalField(max_digits=6, decimal_places=2)
units = models.CharField(max_length=2)
description = models.TextField()
release_date = models.DateField(auto_now_add=True)
inventory = models.IntegerField(default=0, blank=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.name
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
caption = models.CharField(max_length=100)
image = models.ImageField(upload_to='product_images/')
primary = models.BooleanField(default=False)
def __str__(self):
return self.caption
VIEW BRIEF
products = Product.objects.filter(active=1, inventory__gte=1, productimage__primary=True)
TEMPLATE
{% for item in products %}
<a href="{% url 'main:product-detail' id=item.id %}">
<div class="prod_card">
<img src="../media/{{item.productimage.image}}" alt="{{item.productimage.caption}}">
<p>{{item.name|title}} ${{item.price}}</p>
<p>Inventory: {{item.inventory}}</p>
</div>
</a>
{% endfor %}