Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python datastructures into js datastructures using Django templates (lists and dicts)

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 &#39 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}];
like image 624
Matt Alcock Avatar asked Feb 21 '23 06:02

Matt Alcock


1 Answers

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.

like image 190
Thomas Avatar answered Apr 06 '23 07:04

Thomas