How to display multiple images for django model(如何显示Django模型的多幅图像)
本文介绍了如何显示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模型的多幅图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:如何显示Django模型的多幅图像


基础教程推荐
猜你喜欢
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01