Python数据结构使用Django模板(列表和数字) [英] Python datastructures into js datastructures using Django templates (lists and dicts)

查看:100
本文介绍了Python数据结构使用Django模板(列表和数字)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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)

模板文件中有一些基本的JavaScript,这样做是这样的。

  var data ={{data}} 
console.log(data);
// .....其他功能

问题是数据是通过格式如下的模板进入JavaScript,引用了&#39。

  {'书&#39 ;: 4,'年&#39 ;: 2010},{' books&#39 ;: 7,' year&#39 ;: 2011} 

我尝试将python中的jits字符串转储到python中的一个json字符串:

  simplejson.dumps(data)

但没有快乐。任何建议和想法修复?人们如何使用django模板将python数据结构转换成js数据结构



注意:理想情况下,js数据变量将如下所示:

  var data = [{year:2006,books:54},
{year:2007,books:43},
{year:书:41},
{年:2009,书:44},
{年:2010,书:35}];


解决方案

这是django设计的一部分,可以阻止用户生成数据从进入输出未转义。 (XSS预防等)



为了解决这个问题,您需要使用 json.dumps()(pyj = 2.6中的simplejson已被弃用),以确保输出为JS Safe,并且 var data ={{data | safe}}告诉django不要转义该变量的输出。


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}];

解决方案

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.

这篇关于Python数据结构使用Django模板(列表和数字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆