Retrieve info from many-to-many relationship in django temaplate -


i creating blog , have many-to-many relationship between posts , categories.

class category(models.model):     title = models.charfield(max_length=255)     slug = models.slugfield()      def __str__(self):         return self.title  class post(models.model):     title = models.charfield(max_length=255)     subtitle = models.charfield(max_length=255,null=true,blank=true)     published_date = models.datetimefield(auto_now_add=true)     draft = models.booleanfield(default=true)     body = richtextfield(config_name='blog')     slug = models.slugfield()     categories = models.manytomanyfield(category)     featured = models.booleanfield(default=false) 

i trying retrieve the list of categories associated individual post within template can display category titles @ bottom of post.

here template code displays posts not categories.

{% post in blog_posts %}              <div class="post">                 <div class="date">                     {{post.published_date|date:"m"}}                     <span class="day">{{post.published_date|date:"d"}}</span>                     <span>{{post.published_date|date:"y"}}</span>                 </div>                     <div class="entry">                         <div class="page-header">                             <h2 class="post-title"><a href="{% url blog_post post.id post.slug %}">{{post.title}}</a></h2>                         </div>                         <blockquote>                             <p><strong>{{post.subtitle}}</strong></p>                         </blockquote>                         <p>{{post.body|safe}}</p>                         <div class="well well-small">                           <i class="icon-th-list "></i> categories:list categories here                          </div>                     </div> <!--entry div-->             </div><!--post div--> {% endfor %} 

does have thoughts on how retrieve categories specific post? appreciate time , expertise.

you can access categories this

{% category in post.categories.all %}     {{ category.title }} {% endfor %} 

i recommend adding .prefetch_related('categories') queryset in view reduce number of sql queries.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -