4

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}];
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Matt Alcock
  • 12,399
  • 14
  • 45
  • 61
  • I am having the same problem, but my issue is how to turn the python variable strings into js parameters? So in your example above, the 'year' and 'books' variables of python to year and book in the js script. How did you do this? – Mark Apr 13 '14 at 14:48

1 Answers1

8

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.

Thomas
  • 11,757
  • 4
  • 41
  • 57
  • 1
    Do not use this if there is user-generated data included; if used inside a `` as part of the content. Escape all anglebrackets, single quotes and ampersands to JSON `\uxxxx` escape codes *too*! – Martijn Pieters Apr 13 '14 at 15:24