Django:在父模型的详细视图模板中显示外键模型

时间:2019-10-03 18:17:17

标签: python django django-models django-templates foreign-keys

我有以下两种型号:

class SpecimenImage(models.Model):
   image = ImageField(upload_to='images/')
   usi_image = models.ForeignKey('SpecimenRecord', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Unique Specimen Identifier')
   ...

class SpecimenRecord(models.Model):
   usi = models.CharField(primary_key=True, max_length=20, verbose_name='Unique Specimen Identifier')
   species = models.ForeignKey(Species, on_delete=models.SET_NULL, null=True, blank=True)
   locality = models.ForeignKey(Locality, on_delete=models.SET_NULL, null=True, blank=True)
   date = models.DateField(null=True, blank=True)
   collector = models.ManyToManyField(Collector, verbose_name='Collector(s)', null=True, blank=True)
   ...

我有一个SpecimenRecord的通用详细视图:

...
class SpecimenDetailView(generic.DetailView):
    model = SpecimenRecord

这是urls.py:

...
urlpatterns = [
    ...
    path('specimen/<str:pk>', views.SpecimenDetailView.as_view(), name='specimen-detail'),
    ]

我的问题是,如何显示和循环与html模板中的单个SpecimenImage对象关联的所有SpecimenRecord实例?我可以使用SpecimenRecord等轻松显示每个{{ specimenrecord.usi }}的信息,但是我不知道如何显示每个图像。

我尝试将MDN网站上的信息用于一般详细视图(https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views):

{% for copy in book.bookinstance_set.all %}
  <!-- code to iterate across each copy/instance of a book -->
{% endfor %}

这是我在模板specimenrecord_detail.html中尝试的代码:

{% extends "base.html" %}
{% load thumbnail %}

{% block content %}
...
  {% for copy in specimenrecord.specimenimage_set.all %}
    <div class="gallery">
      <img src="{% thumbnail copy.image '1920' as im %}{{ im.url }}{% endthumbnail %}" alt="specimen image"
        srcset="
          {% thumbnail copy.image '544' as im %}  {{ im.url }} {{ im.x }}w{% endthumbnail %},
          {% thumbnail copy.image '768' as im %}  {{ im.url }} {{ im.x }}w{% endthumbnail %},
          {% thumbnail copy.image '992' as im %}  {{ im.url }} {{ im.x }}w{% endthumbnail %},
          {% thumbnail copy.image '1200' as im %}  {{ im.url }} {{ im.x }}w{% endthumbnail %},
          {% thumbnail copy.image '1920' as im %}  {{ im.url }} {{ im.x }}w{% endthumbnail %}"
        alt="specimen image"
        sizes="100vw"
      />
    </div>
  {% endfor %}
{% endblock %}

但是,此代码产生了一个空的<div>。我在做什么错了?

1 个答案:

答案 0 :(得分:0)

玩完代码后,我找到了解决方案。通过将下面的代码包装在<img src>周围,图像将出现在div中:

<a target="_blank" href="{{ copy.image.url }}">
  <img src=.....>
</a>

(我不确定为什么会这样,但很高兴我得到了想要的结果。)