[ad_1]
I have a Django app (3.2) and I am trying to implement filters in Ajax in jquery that will filter all products based on selected filters.
The problem is that Ajax is filtering only areas, not needs and products. How can I implement a nested loop in Ajax so it will work in the same way as my product_list and I will see not the whole area but only relevant products?
views.py
def filter_data(request):
client_type = request.GET.getlist('client_type[]')
business_challange = request.GET.getlist('business_challange[]')
product_list = Area.objects.prefetch_related(Prefetch("need_area", queryset=Need.objects.filter(category_need__product__isnull=False,category_need__product__status=1).distinct())).filter(need_area__category_need__product__isnull=False, need_area__category_need__product__status=1).distinct()
if len(client_type) > 0:
product_list = product_list.filter(need_area__category_need__product__client_type__title__in=client_type).distinct()
if len(business_challange) > 0:
product_list = product_list.filter(need_area__category_need__product__business_challange__title__in=business_challange).distinct()
context = {
'areas': product_list,
}
ajax_template = render_to_string('product-list-ajax.html', context)
return JsonResponse({'data': ajax_template})
product-list-ajax.html
{% for area in areas %}
<div class="border mb-4 pb-4 px-2">
<h2 class="fw-bold my-2">{{area.title}}</h2>
{% for need in area.need_area.all %}
<h4 class="text-muted mt-4">{{need.title}}:</h4>
{% for product_category in need.category_need.all %}
{% for product in product_category.product.all %}
<a href="{{product.get_absolute_url}}" class="pe-2"><span>{{product.title}}</span></a>
{% endfor %}
{% endfor %}
{% endfor %}
</div>
{% endfor %}
product-filters.js
$(document).ready(function(){
$(".ajaxLoader").hide();
$(".form-check-input").on('click', function(){
var filterObj={};
$(".form-check-input").each(function(index,ele){
var filterVal=$(this).val();
var filterKey=$(this).data('filter');
filterObj[filterKey]=Array.from(document.querySelectorAll('input[data-filter="+filterKey+"]:checked')).map(function(el){
return el.value;
});
});
//Ajax
$.ajax({
url: 'filter-data',
data: filterObj,
dataType: 'json',
beofreSend: function(){
$(".ajaxLoader").show();
},
success: function(res){
$("#filteredProducts").html(res.data);
$(".ajaxLoader").hide();
console.log(res)
}
});
});
});
[ad_2]