3

Here is my model

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)

Here is my view:

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})

I want to call featured_image field from gallery model and use it in section.html rendered file. Not able to get this why can't I access this field.

Template code in section.html:

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

Template code in 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 %}

When clicked on a tag it takes me to section.html page but I want to use featured_image on that page too.

cezar
  • 11,616
  • 6
  • 48
  • 84
xxCodexx
  • 438
  • 1
  • 3
  • 15

1 Answers1

1

If you want to use Gallery object in view gallery_section, you must pass that object into your template:

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})

It won't appear automatically or magically in your template. If you're using it when looping over images, you can also do:

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

but for use outside that loop, you must pass image to your template to get it.

GwynBleidD
  • 20,081
  • 5
  • 46
  • 77
  • how to pass image to template outside that loop. – xxCodexx Sep 23 '15 at 13:25
  • First code snippet is for that, if you don't want to use gallery outside of that loop, you don't need to change anything in your views, just access it properly in template. – GwynBleidD Sep 23 '15 at 14:35