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.
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 %}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With