将视图中的Django Queryset传递给模板

时间:2018-01-31 14:07:53

标签: python django django-models django-forms django-queryset

我有一个Django Views,它有一些逻辑可以将正确的类别传递给模板。

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

我无法解决如何将其传递给模板的问题,我的模板代码如下:

            {% 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 %}  

我很确定我的模板语法错误,但如何将特定类别传递给模板?所以,如果我有一个名为&#39; Mains&#39;如何将主电源的所有产品传递给模板。

3 个答案:

答案 0 :(得分:1)

ListView中来自queryset的项目在模板中以object_list形式提供,因此您需要执行以下操作:

{% 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 %}

您可以在ListView documentation中找到详细信息。注意一个名为get_context_data的方法 - 它返回一个变量和值的字典,它将被传递给模板。您总是可以在源代码中找到它以这种方式工作的原因。

答案 1 :(得分:1)

您可以添加以下方法

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变量。您还可以根据需要添加更新上下文字典的数据。

如果您仍想使用get_queryset方法,则可以在模板中以object_list

的形式访问该查询集
{% for product in object_list %}
...
{% endfor %}

答案 2 :(得分:0)

将数据传递到模板上下文的一种更优雅的方法是使用内置的 view 变量。因此,除了覆盖 get_context_data()方法之外,您还可以创建一个返回查询集的自定义方法:

def stores(self):
    return Store.objects.all()

然后您可以在模板中使用它:

{% for store in view.stores %}
  ...
{% endfor %}

另请参阅:

相关问题