Tadewos Bellete
Tadewos Bellete

Reputation: 49

How to display multiple images for django model

Here is my image model, that I tied to the model Product

class Image(models.Model):
    name = models.CharField(blank=True,max_length=20)
    product = models.ForeignKey(Product)
    image = models.ImageField(blank=True,null=True)

    def __str__(self):
        return self.name

Here is the view that I am using to try and display the images def category(request, category_id): categories = Category.objects.all() images = Image.objects.all() products = Product.objects.all() try: category = Category.objects.get(id=category_id) except Category.DoesNotExist: category = None;

    template = loader.get_template('index.html')
    context = {
        'category': category,
        'categories': categories,
        'images': images,
        'products': products
    }
    return HttpResponse(template.render(context,request))

and here is the html

 {% for image in images %}
            <a href="#" class="image"><img src="{{ image.url }}"></a>
 {% endfor %}

I know this definitely wouldn't work,but atleast this code displays the page instead of an error so i have been using it, can anyone please point me in the right direction to dipslay each image associated with each product. Thank you!

Upvotes: 0

Views: 3390

Answers (1)

Vaibhav
Vaibhav

Reputation: 1234

You can try this:

  {% for product in products%}
  <p> {{product.name}}  </p>
    {% for simage in product.image_set.all %}
      {% if simage.image%}
        <a href="#" class="image"><img src="{{ simage.image.url }}"></a>
      {% endif %} 
    {% endfor %}
  {% endfor %}

Upvotes: 1

Related Questions