You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django视图传递Queryset至模板:按分类渲染产品的问题

Fixing Django ListView Queryset Passing to Template

Hey there! The problem you're facing comes down to how Django's ListView names the context variable for your queryset by default. Your template is looking for products, but ListView doesn't use that name automatically—let's fix this with one of two straightforward solutions:

Option 1: Tell ListView to use products as the context variable

Add the context_object_name attribute to your ProductListView class. This explicitly tells Django to pass your filtered queryset to the template under the name products, so you won't need to change your existing template code.

Here's the updated view code:

class ProductListView(ListView):
    model = models.Product
    template_name = "catalogue/catalogue.html"
    context_object_name = 'products'  # This line makes the magic happen

    def get_queryset(self):
        category = self.kwargs.get("category")
        if category:
            # Use models.Product to match your model definition (or import Product first)
            queryset = models.Product.objects.filter(category__iexact=category)
        else:
            queryset = models.Product.objects.all()
        return queryset

Option 2: Update your template to use the default variable name

If you prefer not to modify the view, you can adjust your template to use the default context variable that ListView provides. By default, it uses two names:

  • object_list: Generic name for any ListView queryset
  • product_list: Model-specific name (derived from your Product model, lowercase + _list)

Just replace products with either of these in your template loop:

{% for product in product_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 %}

Quick Check: Ensure Your URL is Configured Correctly

Double-check that your URL pattern is capturing the category parameter properly, so your get_queryset method can access it. For example:

# urls.py
from django.urls import path
from .views import ProductListView

urlpatterns = [
    path('catalogue/', ProductListView.as_view(), name='catalogue-all'),
    path('catalogue/<str:category>/', ProductListView.as_view(), name='catalogue-category'),
]

This ensures when you visit a URL like /catalogue/Mains/, the category value is passed to your view's kwargs dictionary.

内容的提问来源于stack exchange,提问作者Rutnet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:35:47