问题描述
我有一个 Django 视图,它有一些逻辑可以将正确的类别传递给模板.
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 %}
我很确定我的模板语法是错误的,但是如何将特定类别传递给模板?因此,如果我有一个名为Mains"的类别,我如何将 Mains 的所有产品传递给模板.
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.
推荐答案
可以添加如下方法
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
现在,在您的模板中,您可以访问 some_data
变量.您还可以根据需要添加任意数量的数据来更新上下文字典.
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.
如果您仍然想使用 get_queryset
方法,那么您可以在模板中以 object_list
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 %}
这篇关于将视图中的 Django 查询集传递给模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!