简体   繁体   中英

How to use field from one model into other model while rendering a single view in Django

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM