我如何过滤电子商务类别并将链接放在 Django 导航栏中

how can i filter eCommerce category and put links in Django Nav bar

亲爱的。我想过滤我的产品购买类别并将它们动态显示到导航栏中。 所以这是我在基础应用程序中的观点

def shop_page(request):
    context = {
        'items': Item.objects.all()
    }
    return render(request, 'ecommerce/index_shop.html', context)

这是我的基地navbar.html

<ul class="site-menu js-clone-nav d-none d-lg-block">
              <li class="has-children active">
                <a href="{% url 'ecommerce:shop_page'%}">Shop</a>
               
                <ul class="dropdown">
                  <!-- {%for item in category.item.all%}
                  <li><a href="{{item.category.all}}">{{item.get_category_display}}</a></li>
                  {%endfor%} -->

                   <li><a href="#">Clothes and Uniforms</a></li>
                  <li><a href="#">Phones & Accessories</a></li>
                  <li><a href="#">Jewelry & Watches</a></li>
                  <li><a href="#">Bags & Shoes</a></li>
                  <li><a href="#">Beauty & Health, Hair</a></li> 
                </ul>

我想在导航栏中自动添加类别,并在用户单击类别名称时进行过滤

所以请在github.com

上查看我的项目

你应该做的是在上下文中呈现所有内容,然后在 HTML 中呈现它。例如:

class HomePageView(ListView):
    # ...
    def get_context_data(self, **kwargs):
        context['cat'] = ['clothes', 'bags', 'uniforms']

然后您可以在 HTML 中渲染它:

<ul class="...">
  {% for category in cat %}
    <li>{{ category }}</li>
  {% endfor %}
</ul>

至于过滤器,您可能希望为按钮指定一个表单操作,然后 return 将其作为上下文的一部分。

if 'bags' in request.POST:
    context['items'] = Obj.objects.all.filter(name="bags")
<!-- must be a submit button -->
<form action="..." method="post">
  <input type="submit" name="bags" value="List Objects" />
</form>

之后,您将只会获得物品。您可能想做一些修改,因为我没有您的完整代码,但这是它的工作原理。

请记住,第二种 HTML 形式(带按钮的形式)中必须至少有 2 个按钮,因为只有 1 个按钮时它不起作用,否则没有意义...可以看看解释here.

您可以在您的产品模型(或您项目中的任何名称)下创建一个charfield()并将其命名为category,此字段应填写每个产品上传的产品类别类型正在添加。

并为每个类别指定一个模板,然后您可以在模板中进行如下过滤。

example.html:

{% for product in products %}
   {% if product.category == example(whatever the name of the category is) %}
       {{ product.title }}
       {{ product.price }}
   {% emdif %}
{% endfor %}

额外的想法:如果您有一定数量的类别(这是最有可能的),您可以将所有类别放在一个下拉列表中,该列表(将取代 charfield())供发帖人使用上传新产品时可供选择的产品