I have a Django view that returns a list of dicts like so
data = [{'year': 2006, 'books': 54},
{'year': 2007, 'books': 43},
{'year': 2008, 'books': 41},
{'year': 2009, 'books': 44},
{'year': 2010, 'books': 35}]
c = {
'data': data,
}
return render(request, 'template.html', c)
The template file has some basic JavaScript in it that does something like this.
var data = "{{data}}";
console.log(data);
//..... Then other functions
The issue is that the data is coming into the JavaScript via the template formatted like the below with ' for the quotes.
{'books': 4, 'year': 2010}, {'books': 7, 'year': 2011}
I've tried dumping the list of dicts to a json string in the python using:
simplejson.dumps(data)
But no joy. Any suggestions and ideas for a fix? How do people get python datastructures into js datastructures using django templates
Note: Ideally the js data variable would look like this:
var data = [{year: 2006, books: 54},
{year: 2007, books: 43},
{year: 2008, books: 41},
{year: 2009, books: 44},
{year: 2010, books: 35}];
This is part of django's design to stop user generated data from getting into output unescaped. (XSS prevention and such)
To get around this, you will want to use a combination of json.dumps()
(simplejson is deprecated in py>=2.6) to make sure that the output is JS Safe, andvar data = "{{ data|safe }}"
to explicitly tell django not to escape the output of that variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With