Представление списка не работает, но получение контекстных данных происходит

У меня есть ListView, но когда я вызываю его, работает только метод get_context_data (модель новости и категории, а не продукта), когда я пытаюсь отобразить информацию о моделях в шаблонах.

view:

class HomeView(ListView):
    model = Product
    context_object_name='products'
    template_name = 'main/home.html'
    paginate_by = 25

    def get_context_data(self, **kwargs):
        categories = Category.objects.all()
        news = News.objects.all()
        context = {
            'categories' : categories,
            'news' : news,
        }
        context = super().get_context_data(**kwargs)
        return context

Также есть этот фрагмент кода: context = super().get_context_data(**kwargs) Если это было написано ранее: categories = Category.objects.all() Модель Product показывается, а остальные - нет.

base.html

<body>
    ...
    {% include "base/categories.html" %}
    {% block content %}{% endblock %}
</body>

home.html

{% extends 'main/base.html' %}
{% block content %}
<div>
    ...
    <div>
        {% for product in products %}
        {% if product.featured == True %}
        <div>
            <div>
            <a href="">{{ product.author }}</a>
            <small>{{ product.date_posted|date:"F d, Y" }}</small>
            </div>
            <p>Some text..</p>
        </div>
        {% endif %}
        {% endfor %}
    </div>
</div>
{% endblock content %}

categories.html

<div>
    ...
    <div>
        {% for category in categories %}
        <p>{{ category.name }}</p>
        {% endfor %}
    </div>
    
    <div>
        {% for new in news %}
        <p>{{ new.title }}</p>
        {% endfor %}
    </div>
</div>

Проблема в том, что вы переопределяете контекст, но вам нужно его обновить. Попробуйте следующее:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    categories = Category.objects.all()
    news = News.objects.all()
    context.update({
        'categories' : categories,
        'news' : news,
    })
    
    return context

Вы также можете попробовать следующее:

class HomeView(ListView):
    model = Product
    context_object_name='products'
    template_name = 'main/home.html'
    paginate_by = 25

    def get_context_data(self, **kwargs):
        categories = Category.objects.all()
        news = News.objects.all()
        context = super().get_context_data(**kwargs)
        context["categories"]=categories
        context["news"]=news
        return context
Вернуться на верх