从 Django 模板中的产品列表中过滤类别

Filter Categories from list of Products in Django templates

所以我在这个 Django 电子商务网站上工作,我应该根据三个不同的类别过滤我页面上的产品。由于只有三个固定类别,我决定在我的模型 class 中为 Products 创建一个字典,并认为稍后可以使用 {%For%} 循环在我的模板中相应地过滤产品。

它并没有像我预期的那样工作,而且我遇到了错误,可能是因为我对 Django 不太熟悉并且不知道如何绕过它。非常感谢您的帮助! (我附上了一些屏幕截图以供参考)

MODELS.products screenshot

working implementation of for loop that directly shows all products

Views.catalogue

我正在使用 Class 基于视图的解决方案。基本上你想按类别正确显示产品列表。所以解决方法如下

在 views.py 上的视图 class 是这样的:

from django.views.generic import ListView
from .models import Product

class ProductListView(ListView):
    model = Product
    queryset = model.objects.all()
    context_object_name = 'products'
    template_name = 'your-template-path'

    def get_queryset(self):
        queryset = super(ProductListView, self).get_queryset()
        category = self.request.GET.get('category', None)
        if category:
            return queryset.filter(category=category)
        return queryset

现在使用类别关键字在 URL 参数上发送类别值。我没有使用任何身份验证系统。请自行实施

我的建议是您在 for loop 内添加一个 anchor tag,它将具有 category name,然后您可以将其作为 keyword 传递给定义的 url 类别。

例如:

html...

{% for product in products %}
     ...
     # Adding this anchor tag to your existing code within the loop that will display each product's category.
     # Also you can now send this category name to a specific view to filter the products
     
     <a href="{% url 'category' product.category %}">{{ product.category|title }}</a>
     # Notice that I have passed product.category as a keyword in {% url 'category' product.category %} 
     ...
{% endfor %}

现在,在您的 urls.py 文件中,只需创建一个 url 来处理作为关键字传递的类别。

from .views import category_view  # Importing the new view

urlpatterns = [
     ...    
     path('category/<str:category>/', category_view, name='category'),
     ...
]

来自 views.py 文件。

def category_view(request, category): # Accepting the category passed here
     # You can have any other operations in here if necessary

     products = Product.objects.filter(category__iexact=category)

     context = {
          ...
          'products': products,
          ...
     }
     return render(request, 'products.html', context)

这是解决您问题的基本概念。