Manish Gupta
Manish Gupta

Reputation: 4656

how to append django data to javascript

I have a django view which pass two lists to html template like this:

views.py

sale_day = dash[0]
sale_amt = dash[1]
context_dict = {'sale_day':sale_day,
                'sale_amt':sale_amt}
return render(request, 'dashboard/index.html', context_dict)

In html template i can display data using a for loop like:

{% for day in sale_day %}
    {{day}}
{% endfor %}

But i want to pass the data to a javascript tag inside the html file. I passed the lists like:

<script>

var sale_day = {{sale_day|safe}}
var sale_amt = {{sale_amt|safe}} 

Now i want to populate a javascript array from my two lists. My array is like:

data = [
    { day: '1', amt: 100},
    { day: '2', amt: 75},
    ....
]

how to do this?

Upvotes: 3

Views: 918

Answers (2)

Wtower
Wtower

Reputation: 19902

Basically you want to serialize the Python dictionary into a JSON object. There are many ways to do this. The simplest is to use:

import json
json.dumps(data)

To serialize a Django model, take a look at: Django documentation: Serializing Django objects

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599460

Create a dict in your view, dump it to JSON, and use it in the template.

data = data = [{'day': day, 'amt': amt} for day, amt in zip(sale_day, sale_amt)]
json_data = json.dumps(data)
return render(request, 'dashboard/index.html', {"data": json_data})

...

var data = {{ json_data|safe }}

Upvotes: 3

Related Questions