I have a ListView but when I call it only the get_context_data method works (the news and category model, not the product) when I try to display the information of the models in the templates.
view:
JavaScript
x
16
16
1
class HomeView(ListView):
2
model = Product
3
context_object_name='products'
4
template_name = 'main/home.html'
5
paginate_by = 25
6
7
def get_context_data(self, **kwargs):
8
categories = Category.objects.all()
9
news = News.objects.all()
10
context = {
11
'categories' : categories,
12
'news' : news,
13
}
14
context = super().get_context_data(**kwargs)
15
return context
16
There is also this piece of code: context = super().get_context_data(**kwargs) If it’s written before: categories = Category.objects.all() The Product model is show but not the others.
base.html
JavaScript
1
6
1
<body>
2
3
{% include "base/categories.html" %}
4
{% block content %}{% endblock %}
5
</body>
6
home.html
JavaScript
1
20
20
1
{% extends 'main/base.html' %}
2
{% block content %}
3
<div>
4
5
<div>
6
{% for product in products %}
7
{% if product.featured == True %}
8
<div>
9
<div>
10
<a href="">{{ product.author }}</a>
11
<small>{{ product.date_posted|date:"F d, Y" }}</small>
12
</div>
13
<p>Some text..</p>
14
</div>
15
{% endif %}
16
{% endfor %}
17
</div>
18
</div>
19
{% endblock content %}
20
categories.html
JavaScript
1
15
15
1
<div>
2
3
<div>
4
{% for category in categories %}
5
<p>{{ category.name }}</p>
6
{% endfor %}
7
</div>
8
9
<div>
10
{% for new in news %}
11
<p>{{ new.title }}</p>
12
{% endfor %}
13
</div>
14
</div>
15
Advertisement
Answer
The problem is that you override context, but you need to update it. Try this:
JavaScript
1
11
11
1
def get_context_data(self, **kwargs):
2
context = super().get_context_data(**kwargs)
3
categories = Category.objects.all()
4
news = News.objects.all()
5
context.update({
6
'categories' : categories,
7
'news' : news,
8
})
9
10
return context
11