Python data formats in js datastructures using Django templates (lists and dicts)

I have a Django view that returns a list of names such as

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) 

There is some basic JavaScript in the template file that does something like this.

 var data = "{{data}}"; console.log(data); //..... Then other functions 

The problem is that the data comes in JavaScript through a template formatted as shown below: & # 39 for quotes.

 {'books': 4, 'year': 2010}, {'books': 7, 'year': 2011} 

I tried dropping a list of dicts to a json string in python using:

 simplejson.dumps(data) 

But there is no joy. Any suggestions or ideas for a fix? How people get python datastructures in 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}]; 
+4
source share
1 answer

This is part of the django design so that user data does not end up in the output file without saving. (XSS Prevention, etc.)

To get around this, you'll want to use a combination of json.dumps() (simplejson is deprecated in py> = 2.6) to make sure the output is JS Safe, and var data = "{{ data|safe }}" to explicitly indicate django, so as not to run away the output of this variable.

+8
source

Source: https://habr.com/ru/post/1399549/


All Articles