在Django模板中显示图像

时间:2018-12-25 12:05:06

标签: django django-templates

我有这三种模型-“事物”具有关联的“相册”,其中通常包含“事物”的三个或四个“照片”。对于最新的九个“事物”,我想使用“ headquarters.html”模板显示“相册”中事物的第一张照片,以及事物的其他详细信息(例如名称,制造国家)。

以下是我的型号:

class Thing(models.Model):
name = models.CharField(verbose_name = "Item", max_length = 60)
price = models.DecimalField(max_digits = 5, decimal_places = 2)
country_of_manufacture = models.CharField(verbose_name = "Country of Manufacture", max_length = 40)
created_on = models.DateTimeField(verbose_name = "Creation Date", default = django.utils.timezone.now, editable = False)
album = models.OneToOneField(Album, on_delete = models.CASCADE, null = True)

def __str__(self):
    return self.name

class Album(models.Model):
name = models.CharField(verbose_name = "Photo Album", max_length = 60)
created_on = models.DateTimeField(verbose_name = "Creation Date", default = django.utils.timezone.now, editable = False)

def __str__(self):
    return self.name

class Photo(models.Model):
photo_identity = models.ImageField(blank = True, null = True, upload_to="media/%Y/%m/%d/")
photo_in = models.ForeignKey(Album, on_delete = models.PROTECT)
uploaded_on = models.DateTimeField(verbose_name = "Creation Date", default = django.utils.timezone.now, editable = False)

def __str__(self):
    return '%s -- (%s)' % (self.photo_in.name + " Album", self.photo_identity)

这是我的观点。

def headquarters(request, *args, **kwargs):
last_nine = Thing.objects.all().order_by('-id')[:9]
mylist = []
for thing in last_nine:
    mylist.append (thing.album.photo_set.first().photo_identity)
return render(request, 'headquarters.html', {"nine_items" : last_nine, "URL_list" : mylist})

这是我的模板(headquarters.html):

{% for item in nine_items %}
    <div class="col-lg-4 col-sm-6 portfolio-item">
      <div class="card h-100">
        <a href="http://localhost:8000/view_a_thing/{{item.id}}/"><img class="card-img-top" src="{{ **what_do_put_in_here** }}" alt=""></a>
        <div class="card-body">
          <h4 class="card-title">
            <a href="http://localhost:8000/view_a_thing/{{item.id}}">{{item.name}}</a>
          </h4>
          <p class="card-text">Brand: {{item.brand}}</p>
          <p class="card-text">Item ID: {{item.id}}</p>
          <p class="card-text">Item price: {{item.price}}</p>
          <p class="card-text">Made in {{item.country_of_manufacture}}</p>
        </div>
      </div>
    </div>
{% endfor %}

我无法显示“相册”中的第一张照片。什么都没出来。我已经尝试了三天,但没有成功。任何帮助是极大的赞赏。谢谢。

此致, CKLee

1 个答案:

答案 0 :(得分:0)

documentation [Django-doc]中所述,您可以使用与url关联的值的ImageField属性,因此:

<img class="card-img-top" src="{{ item.album.photo_set.first.photo_identity.url }}" alt="">