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

**URL:** <https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727>\
**Category:** Using Django\
**Created:** [January 21, 2022, 9:05pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727 "2022-01-21T21:05:13Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![marly](https://avatars.discourse-cdn.com/v4/letter/m/90db22/32.png) [@marly](https://forum.djangoproject.com/u/marly)\
**Post date:** [January 21, 2022, 9:05pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/1 "2022-01-21T21:05:13Z")

</div>

I have stored some data on localStorage( Itemnames and ItemIds), As shown on this image:[LocalStorage console.log](https://i.stack.imgur.com/I2M6a.jpg)  
now I want to send itemid’s to django views from ajax. Filter the products having those id, and return back to template.

I am trying to pass data to views on this way:

```auto
$(document).ready(function() {
    var compare = localStorage.getItem("comparisionItems");
    var compareObj = JSON.parse(compare);
    
    
    console.log(compare)
    console.log(compareObj)
    
   
      
      $.ajax({
        url: './compare',
        type: "POST",
        data: {'compare_id': compareObj },
        headers: { "X-CSRFToken": $.cookie("csrftoken") },
        dataType: "json",
        success: function (data) {
            console.log(data)
            
        },
        error: function () {
            alert("Some problem on passing data");
        }
        
    });
});

```

And my views is :

```auto
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
    compare_id= request.POST.getlist('compare_id[itemIds]')
    product = get_object_or_404(Products, id=compare_id)
    context={ 'product':product}
    return render (request, './compare.html', context)

```

My views is failing to render expected record. I think I am messed with passing and getting data-types.

Any help will be highly appreciated.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 21, 2022, 9:10pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/2 "2022-01-21T21:10:58Z")

</div>

See the docs for the [HttpRequest object](https://docs.djangoproject.com/en/4.0/ref/request-response/#httprequest-objects)

[request.POST](https://docs.djangoproject.com/en/4.0/ref/request-response/#django.http.HttpRequest.POST) is used to access HTML form data. To access a JSON submission, use [request.body](https://docs.djangoproject.com/en/4.0/ref/request-response/#django.http.HttpRequest.body)

---

<div class="post-metadata">

**Author:** ![marly](https://avatars.discourse-cdn.com/v4/letter/m/90db22/32.png) [@marly](https://forum.djangoproject.com/u/marly)\
**Post date:** [January 21, 2022, 9:20pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/3 "2022-01-21T21:20:07Z")

</div>

I tried this way too :

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['compare_id']['itemIds'] if 'itemIds' in data['compare_id'] else []

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

    context={'products':products}

    return render(request,'./compare.html', context) 

```

Still I am getting error

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 21, 2022, 9:20pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/4 "2022-01-21T21:20:49Z")

</div>

What error are you getting?  
(Please post the _complete_ traceback)

Also, as a side note, that `is_ajax` setting and conditional is likely superfluous - I personally wouldn’t bother with it.

---

<div class="post-metadata">

**Author:** ![marly](https://avatars.discourse-cdn.com/v4/letter/m/90db22/32.png) [@marly](https://forum.djangoproject.com/u/marly)\
**Post date:** [January 21, 2022, 9:22pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/5 "2022-01-21T21:22:49Z")

</div>

# TypeError at /products/compare

string indices must be integers

| Request Method: | POST |
| --- | --- |
| Request URL: | [http://127.0.0.1:8000/products/compare](http://127.0.0.1:8000/products/compare) |
| Django Version: | 3.2.8 |
| Exception Type: | TypeError |
| Exception Value: | string indices must be integers |
| Exception Location: | I:\Projects\djangovenv\Office\bahri\ecommerce\views.py, line 146, in compare |
| Python Executable: | I:\Projects\djangovenv\Scripts\python.exe |
| Python Version: | 3.8.3 |

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 21, 2022, 9:23pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/6 "2022-01-21T21:23:58Z")

</div>

Ok, it would have been better to have the traceback from the console log, but I think we can work with this.

> [@marly](#):
>
> |Exception Location:|I:\Projects\djangovenv\Office\bahri\ecommerce\views.py, line 146, in compare

What is line 146?

---

<div class="post-metadata">

**Author:** ![marly](https://avatars.discourse-cdn.com/v4/letter/m/90db22/32.png) [@marly](https://forum.djangoproject.com/u/marly)\
**Post date:** [January 21, 2022, 9:24pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/7 "2022-01-21T21:24:43Z")

</div>

compare\_ids = data[‘compare\_id’][‘itemIds’] if ‘itemIds’ in data[‘compare\_id’] else []

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 21, 2022, 9:27pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/8 "2022-01-21T21:27:50Z")

</div>

Ok, so in your test case, what specifically is the value of request.body, and therefore `data` at the line prior to that?  
(What does your post request look like?)

---

<div class="post-metadata">

**Author:** ![marly](https://avatars.discourse-cdn.com/v4/letter/m/90db22/32.png) [@marly](https://forum.djangoproject.com/u/marly)\
**Post date:** [January 22, 2022, 7:12am UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/9 "2022-01-22T07:12:31Z")

</div>

{‘compare\_id’: ‘{“images”:["/media/products/testimg.jpg","/media/products/testimg2.jpg"],“itemIds”:[“4”,“1”]}’}

This is what passed

---

<div class="post-metadata">

**Author:** ![marly](https://avatars.discourse-cdn.com/v4/letter/m/90db22/32.png) [@marly](https://forum.djangoproject.com/u/marly)\
**Post date:** [January 22, 2022, 7:22am UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/10 "2022-01-22T07:22:03Z")

</div>

I checked printing the value assigned to **data** , I dont know how can I achieve the task now, could you please guide me?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 22, 2022, 1:08pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/11 "2022-01-22T13:08:39Z")

</div>

Assuming that there’s nothing being misrepresented by the `print` function, it looks like the value part of the object you’re passing is being processed as a string rather than as a nested object.

That gives me a couple ideas you could try - and in no particular order -

- Set the contentType in your AJAX call to `application/json`, and processData to `false`. (See [jQuery.ajax() | jQuery API Documentation](https://api.jquery.com/jquery.ajax/))

- Instead of setting data to `{'compare_id': compareObj }`, just set it to `compareObj`. That also means that your references in your view will change from `data['compare_id']['itemIds']` to `data['itemIds']`.

- Call json.loads on data[‘compare\_id’].

Superficially, I think any one of these would be enough - the choice comes down to what you’re comfortable with. However, it’s possible that you _may_ need to do both of the first two together to get it to work.

Side note: One of the quickest / easiest ways to see what’s being passed is to look at the network tab within your browser’s developer tools. It’ll show you exactly what’s being sent. Also, if you’re going to be working with AJAX calls on a regular basis, you’re going to find it extremely useful to get comfortable with running your code in the context of a debugger.

---

<div class="post-metadata">

**Author:** ![marly](https://avatars.discourse-cdn.com/v4/letter/m/90db22/32.png) [@marly](https://forum.djangoproject.com/u/marly)\
**Post date:** [January 22, 2022, 8:51pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/12 "2022-01-22T20:51:29Z")

</div>

I got the id passed to my **product** variable doing following method:  
I passed data to ajax without json.parse, in my context I passed : data: compare,  
and updated views as following:

```auto
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)      
        context={'products':products}
               return render(request,'./ecommerce/compare.html', context)
    else:
     return render(request,'./ecommerce/compare.html')

```

Now,  
When I print data on html template by doing {{product.name}} it shows blank. I think I should do something with if/else, could you please help me with this?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 22, 2022, 11:43pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/13 "2022-01-22T23:43:50Z")

</div>

When you’re posting code here, you need to surround the code with lines of three backtick - ` characters. That means you’ll have a line of ```, then your code, then another line of ```. That forces the forum software to maintain the formatting of your code, which is critical with Python.

---

<div class="post-metadata">

**Author:** ![marly](https://avatars.discourse-cdn.com/v4/letter/m/90db22/32.png) [@marly](https://forum.djangoproject.com/u/marly)\
**Post date:** [January 23, 2022, 7:41am UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/14 "2022-01-23T07:41:08Z")

</div>

corrected, could you please help now?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 23, 2022, 1:22pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/15 "2022-01-23T13:22:19Z")

</div>

I don’t see anything wrong with your view. (I’ll assume the first `return` statement is indented properly.)  
Next steps I would take would be to verify that `compare_ids` is a list of the right datatypes matching your id field of `Products` and that your `products` queryset is returning the expected results.

If both of those are correct, then we’d need to see the `compare.html` template to see how you’re trying to render the data.

---

<div class="post-metadata">

**Author:** ![marly](https://avatars.discourse-cdn.com/v4/letter/m/90db22/32.png) [@marly](https://forum.djangoproject.com/u/marly)\
**Post date:** [January 23, 2022, 3:51pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/16 "2022-01-23T15:51:00Z")

</div>

Compare.html has simple logic, when the page loads it will send the post data from ajax as shown above and then I am trying to print the product on template via:  
{% for products in products %}  
{{product.name}}  
{% endfor %}

I think first when page loads before sending data will be GET, and then when it sends data it will get records from POST and it should print that data, I am assuming this.  
Should I do something on my views to achieve return on this way?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 23, 2022, 4:09pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/17 "2022-01-23T16:09:22Z")

</div>

> [@marly](#):
>
> {% for products in products %}

This line is incorrect. Look at it carefully, keeping in mind that the following line is:

> [@marly](#):
>
> {{product.name}}

---

<div class="post-metadata">

**Author:** ![marly](https://avatars.discourse-cdn.com/v4/letter/m/90db22/32.png) [@marly](https://forum.djangoproject.com/u/marly)\
**Post date:** [January 23, 2022, 4:22pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/18 "2022-01-23T16:22:49Z")

</div>

sorry I am doing correctly {{products.name}} or {{product.name}} if variable is product. I am aware of this, but data is not showing while on console.log network shows 200 status code. So I think I should do something with views, is there anything that I need to do there?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 23, 2022, 4:45pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/19 "2022-01-23T16:45:59Z")

</div>

The fragment you’ve referenced is not the line I pointed out as having the problem.

What specifically is this line doing?

> [@marly](#):
>
> {% for products in products %}

---

<div class="post-metadata">

**Author:** ![marly](https://avatars.discourse-cdn.com/v4/letter/m/90db22/32.png) [@marly](https://forum.djangoproject.com/u/marly)\
**Post date:** [January 23, 2022, 4:51pm UTC](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727/20 "2022-01-23T16:51:20Z")

</div>

{% for product in products%}

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

its what actually I am doing, though its just showing white space

[Next page](https://forum.djangoproject.com/t/how-can-i-send-localstorage-data-from-javascript-ajax-call-and-print-return-data-from-views-in-django-template/11727.md?page=2)
