Reputation: 1469
I use a generic view to list my categories. I would also like to display the title of each items belonging to these categories. I understand the principle of ListView and DetailView but what about some details in lists ?
Here are my different files:
Models.py
class categories(models.Model):
name = models.CharField(max_length=50,unique=True)
slug = models.SlugField(max_length=100,unique=True)
def __str__(self):
return self.name
class details(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=42)
category = models.ForeignKey('categories', on_delete=models.CASCADE)
def __str__(self):
return self.title
Views.py
class IndexView(generic.ListView):
model = categories
context_object_name = "list_categories"
template_name='show/index.html'
Urls.py
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
]
Index.html
{% load static %}
<p>These is a list of categories</p>
{% for category in list_categories %}
<div class="article">
<h3>{{ category.name }}</h3>
{% for title in category.detail %}
<p> {{title}} </p>
{% endfor %}
</div>
{% endfor %}
Upvotes: 0
Views: 125
Reputation: 2277
You need to first reverse call the details
with related name i.e "categories".
{% load staticfiles %}
<p>These is a list of categories</p>
{% for category in list_categories %}
<div class="article">
<h3>{{ category.name }}</h3>
{% for detail in category.categories.all %}
<p> {{detail.title}} </p>
{% endfor %}
</div>
Be careful you must use all
after reverse all because there could be more then one reverse relation.
Still have any doubts comment it below.
Upvotes: 1