How can I send localstorage data from JavaScript ajax call and print return data from views in Django template

Have you done this?

You can also use the Django shell to test whether the compare_ids you’re receiving generates the proper results with your query.

Yes its printing <QuerySet [<Products: Test product>, <Products: STEIF WELDING HELMET With CONNECTOR>]> when I print Products context.

But its not visible on template even I am doing on correct way. When I check on network inside console on browser data is there but its not visible on site. And header inside Networks shows method as GET

If, in your view, printing context['products'] is showing you the correct data, then the view is working as expected and the problem is in the template.

In template when /compare page loads, it sends POST data from ajax and I am trying to publish data on template obtained from views. But I think the data obtained from views is not printed, its just printing passed from else condition where there is not product/context passed. How can I pass product/context obtained from if condition to else condition?

Or is there any better way I can resolve this?

I don’t understand what you’re trying to say here.

When you wrote:

How were you determining this? What code did you add to your view, and where?

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,'./ecommerce/compare.html', context)
    else:
     return render(request,'./ecommerce/compare.html')

If that print function is being called, then you’re definitely in the if condition side and not the else condition, and therefore the problem is in the template.

and I am just trying to print

                    {{product.name}}
                    {%endfor%}

but its not showing anything. When I check inside network, it shows data:
as below image

[quote=“marly, post:28, topic:11727, full:true”]
and I am just trying to print

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

but its not showing anything. When I check inside network, it shows data:
as below image


[/quote]

We would need to see the complete template, and any base templates that it extends.

How about your Products model. What does that look like? (I thought I had seen it in an earlier comment but I can’t seem to find it now. My apologies if I’m just overlooking it.)

Also, I am aware of some tags being “whitespace” sensitive to some degree. It might be worth cleaning up the whitespace in your tags. (e.g. {% block content %} instead of {% block content%} No idea on whether this this a contributing factor or not, but it’s an easy thing to try.)

class Products(models.Model):
    name = models.CharField(max_length=250,null=True, blank=True,)
    slug = models.SlugField(max_length=200, unique=True,null=True)
    short_description = HTMLField(help_text = "Apply bullet list to short description")
    description = HTMLField(help_text = "Apply paragraph and bullet list to  description for better visibility")
    category = models.ForeignKey(Categories, related_name="products",on_delete=models.SET_NULL,null=True,blank=True,)
    brand = models.ForeignKey(Brands,on_delete=models.CASCADE, default=None, null=True, blank=True,)
    warranty_support = HTMLField()
    product_type = models.CharField(choices=PRODUCT_TYPE, default='simple', max_length=50)
    is_published =models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

I can see product being called inside console, Networks as I have shared screenshot previously but not printed on template I wonder with this odd problem

Problem not resolved yet

Looking over this entire thread, why are you returning html to an Ajax call looking for a json response?

Let me explain what exactly I want to achieve with this. I have or will have some data stored on localstorage. Now I do not want those data to be stored on database but I want to show more details about those data/id on another link. So that, when that dedicated link is loaded, ajax call will happen with document.ready() , I will get id of the item, I will create filter from the obtained id from ajax. now I want to show the detail of those id obtained from ajax to that dedicated link.

What precisely do you mean by “localstorage”? Are you referring to data stored in the browser?

That’s fine. What do you want the view to return? HTML or JSON?

Yes, loclastorage means data stored in browser. I want to print data in above template which I have shared earlier. I am trying with HTML but its not happening. I will appreciate your solution guide/recommendation.

Your ajax call is set up expecting a JSON response.

Should I do anything to expect HTML response? Else, how can I pass JSON via views and print back to template?

It’s your decision with how you want to handle this. You need to make the choice of either having the view render the data and then injecting the html response into the DOM, or getting the response back as JSON, and using that data to populate the DOM.

Django works equally well either way.

Regarding:

and assuming you’re using JQuery, see the docs at jQuery.ajax() | jQuery API Documentation

You might have seen on above code, I am trying to inject with DOM. Can you help me why I am failing?