Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Django Queryset in Views to Template

I have a Django Views which has some logic for passing the correct category to the template.

class ProductListView(ListView):
    model = models.Product
    template_name = "catalogue/catalogue.html"

    def get_queryset(self):
        category = self.kwargs.get("category")
        if category:
            queryset = Product.objects.filter(category__iexact=category)
        else:
            queryset = Product.objects.all()
        return queryset

I can't work out how to pass this to the template, my template code is as below:

            {% for product in products %}
            <tr>   
                <td><h5>{{ product.name }}</h5>
                <p>Cooked with chicken and mutton cumin spices</p></td>
                <td><p><strong>£ {{ product.price }}</strong></p></td>
                <td class="options"><a href="#0"><i class="icon_plus_alt2"></i></a></td>
            </tr>
            {% endfor %}  

I am pretty sure my template syntax is wrong, but how do I pass the particular category to the template? So if I have a category called 'Mains' how do I pass all the products for mains to the template.

like image 417
Rutnet Avatar asked Oct 18 '25 14:10

Rutnet


2 Answers

You can add the following method

def get_context_data(self, **kwargs):
    context = super(ProductListView, self).get_context_data(**kwargs)
    some_data = Product.objects.all()
    context.update({'some_data': some_data})
    return context

So now, in your template, you have access to some_data variable. You can also add as many data updating the context dictionary as you want.

If you still want to use the get_queryset method, then you can access that queryset in the template as object_list

{% for product in object_list %}
...
{% endfor %}
like image 88
Dalvtor Avatar answered Oct 20 '25 02:10

Dalvtor


Items from queryset in ListView are available as object_list in the template, so you need to do something like:

{% for product in object_list %}
            <tr>   
                <td><h5>{{ product.name }}</h5>
                <p>Cooked with chicken and mutton cumin spices</p></td>
                <td><p><strong>£ {{ product.price }}</strong></p></td>
                <td class="options"><a href="#0"><i class="icon_plus_alt2"></i></a></td>
            </tr>
            {% endfor %}

You can find details in the ListView documentation. Note a method called get_context_data - it returns a dictionary of variables and values, that will be passed to templates. You can always find why it works in this way in the source code.

like image 41
Andrey Rusanov Avatar answered Oct 20 '25 02:10

Andrey Rusanov