我想用这样的

我在做一个像图像一样的牛皮纸板。
我可以在细节页显示图像。但是我不能显示图片公告栏列表(索引页)。
如何将图片添加到公告栏列表中?
玩具/Models.py
class NewBornProduct(models.Model):
type = models.ForeignKey(Type,on_delete=models.PROTECT)
name = models.CharField(,max_length=30)
content = models.TextField()
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
price = models.IntegerField(null=False)
class NewBornProductImage(models.Model):
product = models.ForeignKey(NewBornProduct,on_delete=models.CASCADE)
image = models.ImageField(upload_to="newborn/%Y/%m/%d")
def delete(self, using=None, keep_parents=False):
self.image.delete()
return models.Model.delete(self, using=using, keep_parents=keep_parents)玩具/views.py
def newborn(request):
obj = NewBornProduct.objects.all()
return render(request,'toy/newborn.html',{'obj':obj})toy/newborn.html
{% for post in obj %}
<tr>
<th>{{post.id}}</th>
<th> i want to show image here!</th> <-------- Here!
<th>
<a href="{% url 'toy:newborndetail' post.id %}">{{post.name}}</a>
</th>
<th>{{post.price}}</th>
<th>{{post.amount}}</th>
<th>{{post.pub_date}}</th>
</tr>
{% endfor %}我不知道如何称呼这个图像,因为另一个很好。
你有什么想法吗?
发布于 2018-10-18 08:50:37
如果你想要的是“第一个图像,如果有”:
{% for post in obj %}
<tr>
<th>{{post.id}}</th>
<th>
{% with post.newbornproductimage_set.first as img %}
{% if img %}<img src="{{ img.image.url }}" />{% endif %}
{% endwith %}
</th>
<th>
<a href="{% url 'toy:newborndetail' post.id %}">{{post.name}}</a>
</th>
<th>{{post.price}}</th>
<th>{{post.amount}}</th>
<th>{{post.pub_date}}</th>
</tr>
{% endfor %}还注意到:
1/您的标记是错误的,您应该使用td,而不是th (th是表头)
2/将产品命名为queryset obj和products实例post并不能帮助wrt/可读性/可维护性。您应该将obj重命名为products (复数,表示集合),将post重命名为product。
https://stackoverflow.com/questions/52869967
复制相似问题