Django отключение флажков в зависимых списках
У меня есть 3 списка чекбоксов, и я хотел бы отключить все ненужные чекбоксы в моем HTML файле, если нет соответствующих продуктов, связанных с этим продуктом, и динамически изменять число подсчета.
На данный момент мне удалось отобразить общее количество элементов для каждого флажка, но я не уверен, как сделать подсчет динамическим, чтобы если пользователь выберет флажок 1 в списке команд, то номера в других списках будут корректироваться и отображать соответствующий подсчет.
Если пользователь выбирает чекбокс 1 в списке команд, я хочу отключить все изменения от этого:
<input class="form-check-input" type="checkbox" value="{{object.title}}" id="{{object.title}}" data-filter="type">
К этому:
<input class="form-check-input" type="checkbox" value="{{object.title}}" id="{{object.title}}" data-filter="type" disabled>
views.py
class Search(LoginRequiredMixin, ListView):
login_url = 'login'
redirect_field_name = 'login'
template_name = 'product-list.html'
model = Product
queryset = Product.objects.filter(status=1)
def get_context_data(self, **kwargs):
context = super(Search, self).get_context_data(**kwargs)
type = Type.objects.annotate(type_count=Count('type_product', filter=Q(type_product__status=1)))
role = Role.objects.annotate(role_count=Count('role_product', filter=Q(role_product__status=1)))
leading_team = Team.objects.annotate(team_count=Count('product', filter=Q(product__status=1)))
product_list = Product.objects.filter(status=1)
context['product_type'] = product_type
context['role'] = role
context['leading_team'] = leading_team
context['product_list'] = product_list
return context
#Filter data
def filter_data(request):
type = request.GET.getlist('product_type[]')
role = request.GET.getlist('role[]')
leading_team = request.GET.getlist('leading_team[]')
product_list = Product.objects.filter(status=1)
if len(type) > 0:
product_list = product_list.filter(type__title__in=type).distinct()
if len(role) > 0:
product_list = product_list.filter(service_role__title__in=role).distinct()
if len(leading_team) > 0:
product_list = product_list.filter(team__title__in=leading_team).distinct()
print(product_list)
context = {
'areas': product_list,
}
ajax_template = render_to_string('product-list-ajax.html', context)
return JsonResponse({'data': ajax_template})
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)
}
});
});
});
product-list.html
<div class="row py-4">
<div class="col-xs-12 col-md-4 border filters">
<div class="filter-container">
<span class=" fw-bold f-12">Client type</span>
{% for object in type %}
<div class="form-check d-flex">
<input class="form-check-input" type="checkbox" value="{{object.title}}" id="{{object.title}}" data-filter="type">
<label class="form-check-label ps-2" for="{{object.title}}">
{{object.title}}
</label>
<span class="ms-auto ps-2 text-muted f-12">{{object.type_count}}</span>
</div>
{% endfor %}
</div>
<div class="filter-container">
<strong class="f-12">Service role</strong><br>
{% for object in role %}
<div class="form-check d-flex">
<input class="form-check-input" type="checkbox" value="{{object.title}}" id="{{object.title}}" data-filter="role">
<label class="form-check-label ps-2" for="{{object.title}}">
{{object.title}}
</label>
<span class="ms-auto ps-2 text-muted f-12">{{object.role_count}}</span>
</div>
{% endfor %}
</div>
<div class="filter-container">
<strong class="f-12">Team</strong><br>
{% for object in leading_team %}
<div class="form-check d-flex">
<input class="form-check-input" type="checkbox" value="{{object.title}}" id="{{object.title}}" data-filter="leading_team">
<label class="form-check-label ps-2" for="{{object.title}}">
{{object.title}}
</label>
<span class="ms-auto ps-2 text-muted f-12">{{object.team_count}}</span>
</div>
{% endfor %}
</div>
</div>
<div class="col-xs-12 col-md-8" id="filteredProducts">
<p class="ajaxLoader">Loading data...</p>
{% for product in areas %}
<a href="{{product.get_absolute_url}}" class="rounded-pill bg-hubble text-dark f-12 p-2 tag-extra-style">{{product.title}}</a>
{% endfor %}
</div>