how can i get all images of item into context i tried {% for image in item.images.all %} in template but it doesn’t work. i dunno how to filter it , ty for ur answer
models
class Item(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=True) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE, null=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='photos/%Y/%m/%d/', null=True) size = ArrayField(models.CharField(max_length=255)) price = models.PositiveIntegerField() on_sale = models.BooleanField(default=0) discount = models.PositiveIntegerField(null=True, blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('single_product', kwargs={'slug': self.slug}) def get_sale(self): price = int(self.price * (100 - self.discount) / 100) return price class ItemImage(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True, related_name='images') images = models.ImageField(upload_to='photos/%Y/%m/%d/', null=True) def __str__(self): return self.item.name
views
class ItemDetail(DetailView): model = Item context_object_name = 'item' template_name = 'essense/single-product-details.html' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs)
Advertisement
Answer
You’re pretty close. In your template tag {% for image in item.images.all %}
, image
refers to an instance of your ItemImage model. You need to reference the ImageField within that model, which you’ve named images
. So, instead of
src="{{ image.url }}"
use src="{{ image.images.url }}"
<div className="single_product_thumb clearfix"> <div className="product_thumbnail_slides owl-carousel"> {% for image in item.images.all %} <img src="{{ image.images.url }}" alt="" width="360" height="539"> {% endfor %} </div> </div>```