Как получить доступ к переменным шаблона в ajax jquery в javascript с помощью шаблона Django

У меня есть javascript, содержащий ajax jquery, который обновляет шаблон на основе возвращенных данных, как показано ниже -

=============================================================== product-filter.js находится ниже code

$(document).ready(function(){
    $(".ajaxLoader").hide();
    $(".filter-checkbox").on('click',function(){
        var _filterObj={};
        $(".filter-checkbox").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;
            });
        });
        //Run Ajax
        $.ajax({
            url:'/filter-data_b/1',
            data: _filterObj,
            dataType: 'json',
            beforeSend: function(){
                $(".ajaxLoader").hide();
            },
            success:function(res){
                console.log(res);
                $("#filteredProducts_b").html(res.data);
                $(".ajaxLoader").hide();
            }
        })
    });

=============================================================== Я могу заставить это работать с /filter-data_b/1, где 1 - brand_id, который жестко закодирован, и я хочу знать, как получить это из шаблона, из которого вызывается product-filter.js. код /filter-data_b/1 в views.py и urls.py выглядит следующим образом

urls.py

urlpatterns = [
    path('', views.home,name='home'),
    path('brand_product_list/<int:brand_id>', views.brand_product_list,name='brand_product_list'),
    path('filter-data_b/<int:brand_id>',views.filter_data_b,name='filter_data_b'),
]

================================================================= views.py is

def filter_data_b(request,brand_id):
    colors=request.GET.getlist('color[]')
    categories=request.GET.getlist('category[]')
    brands=request.GET.getlist('brand[]')
    sizes=request.GET.getlist('size[]')
    flavors=request.GET.getlist('flavor[]')
    allProducts=ProductAttribute.objects.filter(brand=brand_id).order_by('-id').distinct()
    if len(colors)>0:
        allProducts=allProducts.filter(productattribute__color__id__in=colors).distinct()
    if len(categories)>0:
        allProducts=allProducts.filter(category__id__in=categories).distinct()
    if len(brands)>0:
        allProducts=allProducts.filter(brand__id__in=brands).distinct()
    if len(sizes)>0:
        allProducts=allProducts.filter(productattribute__size__id__in=sizes).distinct()
    if len(flavors)>0:
        allProducts=allProducts.filter(productattribute__flavor__id__in=flavors).distinct()
    t=render_to_string('ajax/product-list_b.html',{'data':allProducts})
    return JsonResponse({'data':t})

===========================================================================

Вот как можно сделать доступ к переменной шаблона Django во внешнем .js файле :

  1. В вашем шаблоне, где вы вызываете внешний .js файл

     // The order is matter, declare the variable before try to access in your external .js file
     <script>
         let object_id = {{object_id}}  // Assume that 'object_id' is in the the context data of the template.
         let url = {% url 'filter_data_b' object_id %}
     </script> 
     <script src="{% static 'product-filter.js' %}"></script>
    
  2. В вашем внешнем .js файле

     $.ajax({
         url: url, // Declared above
         ...  
     })
    
Вернуться на верх