1

Code is showing:

'ManyRelatedManager' object is not iterable

from django.shortcuts import render
from .models import Post

def index(request):
    parms = {
        'posts': Post.objects.filter(publish=True),
    }
    return render(request, 'index.html', parms)

index.html:

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

<div class="site-section py-0">
  <div class="owl-carousel hero-slide owl-style">
    {% for post in posts|slice:":5" %}
    <div class="site-section">
      <div class="container">
        <div class="half-post-entry d-block d-lg-flex bg-light">
          <div class="img-bg" style="background-image: url({{post.thumbnail.url}})"></div>
          <div class="contents">
            <span class="caption">{{post.author.user.username}}</span>
            <h2><a href="blog-single.html">{{post.title}}</a></h2>
            <p class="mb-3">{{post.overview}}</p>

            <div class="post-meta">
              <span class="d-block">

                {% for cate in post.categories %}
                  <a href="#">{{cate.title}}</a>
                {% endfor %}

              </span>
              <span class="date-read">{{post.time_upload}}<span class="mx-1">&bullet;</span>{{post.read}} reads<span class="icon-star2"></span></span>
            </div>

          </div>
        </div>
      </div>
    </div>
    {% endfor %}
  </div>
</div>
aaron
  • 39,695
  • 6
  • 46
  • 102

1 Answers1

0

post.categories is a manager, not a QuerySet, you should use .all to access the QuerySet:

{% for cate in post.categories.all %}
    <a href="#">{{cate.title}}</a>
{% endfor %}

You can boost efficiency with .prefetch_related(…) [Django-doc] in the view:

def index(request):
    parms = {
        'posts': Post.objects.filter(publish=True).prefetch_related('categories')
    }
    return render(request, 'index.html',parms)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555