3

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?

2 Answers 2

3

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 }}
Sign up to request clarification or add additional context in comments.

1 Comment

Shouldn't it be {{data|safe}} in html instead of {{json_data|safe}}?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.