如何在Django中渲染单个视图时将一个模型中的字段用于其他模型

时间:2015-09-23 12:41:00

标签: python django blogs mezzanine

这是我的模特

class Gallery(models.Model):
    title = models.CharField(max_length=30)
    description = models.TextField(blank=True)
    featured_image = models.ImageField(upload_to="gallery")

    def __str__(self):
        return u'{}'.format(self.title)

class GalleryImage(models.Model):
    title = models.CharField(max_length=50, blank=True)
    description = models.TextField(blank=True)
    gallery = models.ForeignKey(Gallery)
    image = models.ImageField(upload_to="gallery")

    def __str__(self):
        return u'{}'.format(self.title)

以下是我的观点:

def gallery(request):
   galleries = Gallery.objects.all()
    return render(request, "gallery/home.html", {'galleries': galleries})


def gallery_section(request, gallery_id):
    gallery_images = GalleryImage.objects.filter(gallery_id=gallery_id)
    return render(request, "gallery/section.html",{'gimages': gallery_images})

我想从图库模型中调用featured_image字段,并在section.html呈现的文件中使用它。 无法理解为什么我无法访问此字段。

section.html中的模板代码:

.about{
  background-image: url({{ gallery.featured_image.url }});
  background-size: cover;
 }

home.html中的模板代码:

{% for gallery in galleries %}
    <a href="gallery/{{ gallery.id }}">
        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-6 people-desc text-center">
            <img src="{{ gallery.featured_image.url }}" alt="" class="img-responsive people">
            <h4>{{ gallery.title }}</h4>
        </div>
    </a>
{% endfor %}

点击代码后,我会转到section.html页面,但我也希望在该页面上使用featured_image

1 个答案:

答案 0 :(得分:1)

如果要在视图Gallery中使用gallery_section对象,则必须将该对象传递到模板中:

def gallery_section(request, gallery_id):
    gallery = Gallery.objects.get(id=gallery_id)
    gallery_images = GalleryImage.objects.filter(gallery_id=gallery_id)
    return render(request, "gallery/section.html",{'gimages': gallery_images, 'gallery': gallery})

它不会自动或神奇地出现在您的模板中。如果您在循环图像时使用它,您也可以执行以下操作:

{% for image in gimages %}
    {% image.gallery.featured_image.url %}
{% endfor %}

但要在该循环之外使用,您必须将图像传递给模板才能获得它。