首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用模板在板上显示图像?

如何用模板在板上显示图像?
EN

Stack Overflow用户
提问于 2018-10-18 08:30:23
回答 1查看 115关注 0票数 1

我想用这样的

我在做一个像图像一样的牛皮纸板。

我可以在细节页显示图像。但是我不能显示图片公告栏列表(索引页)。

如何将图片添加到公告栏列表中?

玩具/Models.py

代码语言:javascript
复制
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

代码语言:javascript
复制
def newborn(request):
   obj = NewBornProduct.objects.all()
   return render(request,'toy/newborn.html',{'obj':obj})

toy/newborn.html

代码语言:javascript
复制
{% 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 %}

我不知道如何称呼这个图像,因为另一个很好。

你有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-18 08:50:37

如果你想要的是“第一个图像,如果有”:

代码语言:javascript
复制
{% 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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52869967

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档