从Django模板中的产品列表中筛选类别



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

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

MODELS.products屏幕截图

直接显示所有产品的for循环的工作实现

Views.catalogue

我的建议是,在具有category namefor loop内部添加一个anchor tag,然后可以将其作为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)

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

我正在为解决方案使用基于类的视图。基本上你想显示的产品列表按类别权利。因此,解决方案如下。

在views.py上,视图类如下:

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参数上的类别值。我没有使用任何身份验证系统。请在您自己的上实现

最新更新