Home > Net >  List View is not working but get_context_data() works
List View is not working but get_context_data() works

Time:11-23

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:

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

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

<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>

CodePudding user response:

The problem is that you override context, but you need to update it. Try this:

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

CodePudding user response:

You can also try this:

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
  • Related