Search code examples
pythondjangocategories

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


dears. I wanna filter my product buy categories and show them into navbar dynamically. so this is my view in the base application

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

and this is my base 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>

I wanna add automatically categories in the navbar and put filtering when user click on a category name

so please check my project on github.com


Solution

  • What you should do is to have everything rendered in the context, and then you render it in HTML. For example:

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

    and then you can render it in your HTML as such:

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

    As for the filters, you might want to assign your button a form action, and then you return it as a part of your context.

    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>
    

    after this, you will only get the items. You might want to do some amendments as I don't have your full code, but this is briefly how it works.

    Although keep in mind, you must have at least 2 buttons in the second HTML form (the one with buttons) as it doesn't work with only 1 button otherwise there is no point... you can look at the explanations here.