简体   繁体   中英

How to print Django Ajax return as Template Data?

I want to print Products data returned by following views on template. When I check the context its printing the correct data but when I try to print data in template it shows nothing. I checked Networks inside browser console, data is called there but I dont know why its not printing to views

Template

 {% for product in products%}
                    {{product.name}}
                    {%endfor%}

My Ajax:

$(document).ready(function() {
    var compare = localStorage.getItem("comparisionItems");
    var compareObj = JSON.parse(compare);
    
    
    
    console.log(compareObj)
    
   
      
    $.ajax({
      url: './compare',
      type: "POST",
      data: compare,
      headers: { "X-CSRFToken": $.cookie("csrftoken") },
      dataType: "json",
      contentType : "application/json",
      processData: "false",
      success: function (data) {
        location.reload();
          
       },
      
    });
});

Views.py

def compare(request):
    is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
    if is_ajax and request.method == "POST":             
        data = json.loads(request.body)     
        compare_ids = data['itemIds']      
        products = Products.objects.filter(id__in=compare_ids)   
        print(products)   
        context={'products':products}
        return render(request,'./compare.html', context)
    else:
     return render(request,'./compare.html')

QuerySets are lazy!
When you call print() function, products queryset evaluate immediately

You can use all() so it evaluate in your template:

products = Products.objects.filter(id__in=compare_ids).all()

Also take a look at this documentions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM