Jorge López
Jorge López

Reputation: 523

Not able to display in Template the foreign key using ListView

I'm trying to display a photographic session with all of it photos, so I have the session name in one model and I have the pictures in another model linked by a foreign key. I'm not able to display it in the HTML I'm not sure if I'm using the ListView get_context_data correctly and I'm certainly sure the the html code is not correct but I have not found how to do it.

views.py

class SessionPictures(generic.ListView):

    model = PostSession
    template_name = 'photoadmin/gallery.html'

    def get_context_data(self, **kwargs):
        context = super(SessionPictures, self).get_context_data(**kwargs)
        context['picture'] = Images.objects.all()
        return context

models.py

class PostSession(models.Model):
    session_name = models.CharField(max_length=25)
    created_date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return str(self.session_name)


class Images(models.Model):
    name = models.ForeignKey(
        PostSession, related_name='images', on_delete=models.CASCADE, null=True, blank=True)
    picture = models.ImageField(upload_to='pictures')

html

{% extends 'base.html' %}
{% load static %}

{% block content %}


<h2>Images</h2>
<ul>
    {% for session in object_list %}
    <li>{{ session.session_name }}</li>
    <ul>

        <li>{{session.picture_set.all.url}}</li>

    </ul>
    {% endfor %}
</ul>



{% endblock %}

I'm expecting this:

Woods

Beach

Upvotes: 0

Views: 53

Answers (1)

ruddra
ruddra

Reputation: 51988

As you already defined related_name="images" in Images model, so, session.images_set attribute won't work with PostSession.

class Images(models.Model):
    name = models.ForeignKey(
        PostSession,related_name='images', on_delete=models.CASCADE, null=True, blank=True)

Instead, use session.image.all in template(FYI: it returns a queryset, so you need to iterate through it to get the image object):

{% for session in object_list %}
    <li>{{ session.session_name }}</li>
    <ul>
        {% for i in session.images.all %}
            <li> i.picture.url </li>
        {% endfor %}
    </ul>
{% endfor %}

More information on reverse relation can be found in documentation.

Upvotes: 1

Related Questions