Armin
Armin

Reputation: 157

What is wrong with my nested for Loop in a django Template?

I am trying to create a template with Django that loops through Posts and for each Post loops through all Pictures. I already looked at some answers to other Questions but I can not find my error.

Models:

    class Post(models.Model):
        Post_Title = models.CharField(max_length=200)
        Post_pub_date = models.DateField('date published')
        Post_Author = models.CharField(max_length=100)
        Post_Text = models.TextField()
        def __str__(self):
            return self.Post_Title

    class Picture(models.Model):
        Post = models.ForeignKey(Post, on_delete=models.CASCADE)
        Picture = models.ImageField()
        Picture_Name = models.CharField(max_length=100, null=True, blank=True)
        def __str__(self):
            return self.Picture_Name

Views:

    class PostView(generic.ListView):
        template_name = 'myblog/index.html'
        context_object_name = 'Post_List'

        def get_queryset(self):
            """
            Returns Posts
            """
            return Post.objects.order_by('-Post_pub_date')

Template:

    {% for Post in Post_List %}
      <h1 class="mb-4">{{Post.Post_Title}}</h1>
      <span class="category">{{Post.Post_Author}}</span>
      <span class="mr-2">{{Post.Post_pub_date}}</span> 
      <div class="post-content-body"><p>{{Post.Post_Text}}</p>

      {% for Picture in Post.Picture_set.all %}
        <div class="col-md-12 mb-4 element-animate">
          <h2>{{Picture.Picture_Name}}</h2>
          <img class="col-md-12 mb-4 element-animate" src="{{ MEDIA_URL }}{Picture.Picture}}">
        </div>  
      {% endfor %}
      </div>
    {% endfor %}

The Post_Title, Post_Author, Post_pub_date and Post_Text are displayed fine. Just the nested For loop is not producing any Picture_Name or Picture as if the Picture_set.all is empty.

As mentioned above I tried to find my error in different Posts like this but could not find it.

Thanks for your help.

Upvotes: 0

Views: 708

Answers (2)

Aleksandr Kholiavskyi
Aleksandr Kholiavskyi

Reputation: 106

Following relationship backward, you need to write related model name from a small letter, even if model name starts from large letter:

{% for Picture in Post.picture_set.all %}

This is how it works in Django shell and i suppose in templates it is the same.

Upvotes: 1

BushLee
BushLee

Reputation: 65

The issue isn't the nested for loop it's the view.It only returns a query for your Post, you don't pass any Photos to your template.

Upvotes: 0

Related Questions