Search code examples
pythondjangodjango-filter

Filter Products by Catagory in Django


I have a filter list on my home page:

<!-- ? Filter -->
<div class="filter border-top border-bottom row">
    <a href="#">
        <img src="{% static 'store/images/bottoms.png' %}" alt="">
    </a>
    <a href="#">
        <img src="{% static 'store/images/outerwear.png' %}" alt="">
    </a>
    <a href="#">
        <img src="{% static 'store/images/tshirt.png' %}" alt="">
    </a>
    <a href="#">
        <img src="{% static 'store/images/shoes.png' %}" alt="">
    </a>
    <a href="#">
        <img src="{% static 'store/images/skateboard.png' %}" alt="">
    </a>

and trying to filter with something like this:

class ProductListView(ListView):
    model = Product
    template_name = "store/home.html"

    def get_queryset(self):
        catagory = catagory.objects.filter(catagory)

Can I pass the catagory name of the icon I click to the view to filter it? And also can I pass the filter back my home page (thats already listing all Products on) ?

This is my home view:

class ProductListView(ListView):
    model = Product
    template_name = "store/home.html"
    context_object_name='products'
    ordering = ['-date_posted']

Would it be easier to add the queryset to this and set the filter to all as default? Any help appreciated thank you.


Solution

  • Your links should look something like:

    <a href="{% url product_filter filter=bottoms %}">
        <img src="{% static 'store/images/bottoms.png' %}" alt="">
    </a>
    
    # urls.py
    path(r'product/<filter>/', ProductListView.as_view(), name='product_filter')),
    

    Then you would just need to catch the parameter in the View, and filter the list on that.


    Edit: Adding response and code from question in comments for better formatting.

    class ProductListView(ListView): 
        model = Product 
        template_name = "store/filter.html" 
        context_object_name='products' 
        ordering = ['-date_posted'] 
    
        def get_queryset(self): 
            return Product.objects.filter(catagory__name=self.kwargs['filter']))