从Django模板中转义JSON数据的正确方法 [英] Right way to escape JSON data from django template

查看:918
本文介绍了从Django模板中转义JSON数据的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字典从Django视图传递到javascript文件.该词典是根据站点用户填充的数据库构建的.这两种方法在安全性上有什么区别?

I want to pass a dictionary from django view to a javascript file. The dictionary is built from a database populated by site users. What's the difference between these 2 methods in terms of security?

  1. var mydata = JSON.parse("{{mydata|escapejs}}");

var mydata = {{ mydata|safe }};

此外,django上的 doc 表示: escapejs:这不会使字符串在HTML中安全使用.您能给我看一个不安全的例子吗?我该如何确保它安全?

Further, the doc at django says this for escapejs : This does not make the string safe for use in HTML. Could you show me an example of how it's unsafe & how can I make it safe.

推荐答案

以下字典可能会在没有适当转义的情况下中断您的页面:

The following dictionary can break your page without proper escaping:

{'x':'</script><b>HELLO</b>'}

内部标签,您可以在视图中json.dumps进行标记,然后使用escapejs保持安全.

Inside tags, you can json.dumps it in your view and then use escapejs to stay safe.

(我相信解释的意思是,如果要在HTML中显示json.dumps的输出,可以在<pre>标记中说,只需确保不使用safeescapejs将其转义即可. )

(I believe the explanation means that if you want to show the output of json.dumps in HTML, let's say in a <pre> tag, just make sure it is escaped by not using safe or escapejs.)

这篇关于从Django模板中转义JSON数据的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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