如何显示Django模型的多幅图像 [英] How to display multiple images for django model

查看:30
本文介绍了如何显示Django模型的多幅图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的图像模型,我将其绑定到模型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
以下是我用来尝试和显示图像的视图 定义类别(请求,CATEGORY_ID): 类别=Category.objects.all() 图像=Image.objects.all() Products=Product.objects.all() 尝试: 类别=Category.objects.get(id=类别id) 除Category.DoesNotExist外: 类别=无;

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

这里是html

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

我知道这肯定不会起作用,但至少这个代码显示的是页面而不是错误,所以我一直在使用它,有人能指给我正确的方向来显示与每个产品相关的每个图像吗? 谢谢!

推荐答案

您可以尝试:

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

这篇关于如何显示Django模型的多幅图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆