Home > Enterprise >  how to access template variables in ajax jquery in javascript using Django template
how to access template variables in ajax jquery in javascript using Django template

Time:10-27

I have got a javascript containing ajax jquery which refreshes a template based on the data returned as shown below -

product-filter.js is below 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();
            }
        })
    });

I am able to get this working with /filter-data_b/1 where 1 is brand_id which is hard-coded and I want to know how to get this from the template where product-filter.js is called from the /filter-data_b/1 code in views.py and urls.py is as shown below

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})

CodePudding user response:

This is how you can do to access a Django template variable in a external .js file :

  1. In your template where you call the external .js file

     // 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' brandid %}
     </script> 
     <script src="{% static 'product-filter.js' %}"></script>
    
  2. In your external .js file

     $.ajax({
         url: url, // Declared above
         ...  
     })
    
  • Related