0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.