Difficulty using multiple filters simultaneously in Django view with HTMX

I'm encountering an issue with using multiple filters simultaneously in a Django view while incorporating HTMX for asynchronous updates. Here's a breakdown of the relevant code and the problem I'm facing:

Html Requests:

<input id="searchInput" class="form-control mb-4" type="search" name="searchInput"
             placeholder="Procure produtos pelo nome..."
             hx-get="{% url 'filter_products' %}?searchInput={{ searchInput.value }}"
             hx-trigger="input changed delay:500ms, search" hx-target="#search-results">

<select name="name_category" class="form-select px-0 py-0" multiple aria-label="multiple select example"
                  hx-get="{% url 'filter_products' %}"
                  hx-trigger="change"
                  hx-target="#search-results">

Filter View:

def filter_products(request):
    category_names = request.GET.getlist('name_category', [])
    search_query = request.GET.get('searchInput')
    print(search_query)
    print(category_names)

    # Start with all products
    products = Products.objects.all()

    # Apply category filter if any category is selected
    if category_names:
        category_filters = Q()
        for category_name in category_names:
            category_filters |= Q(categoryproducts__category__name_category=category_name)
        products = products.filter(category_filters)

    # Apply search filter if a search query is provided
    if search_query:
        products = products.filter(title__icontains=search_query)

    # Render the response using the products found
    html = render_to_string('products/products_list_partial.html', {'products': products})
    return HttpResponse(html)

The issue arises when I attempt to use both filters simultaneously. If I select a category while a search query is applied (or vice versa), the other filter gets cleared. For instance, if I have a search query applied and then select a category, the search query disappears, and only the category filter is applied.

How can I modify my code to enable the use of both filters simultaneously so that the product list updates based on changes to both the search query and selected categories?

I tried changing the view without sucess. One thing that worked but can't be used is updating hx-trigger to every 1 second which will pass the two values and not just one don't know why...

Back to Top