PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 6, 2022

[FIXED] How to display multiple images for django model

 September 06, 2022     django, django-models, html, image, web-deployment     No comments   

Issue

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!


Solution

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 %}


Answered By - Vaibhav
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing