Passing objects from Django to Javascript DOM

前端 未结 14 1120
野的像风
野的像风 2020-12-04 21:26

I\'m trying to pass a Query Set from Django to a template with javascript.

I\'ve tried different approaches to solve this:

1. Normal Approach - Javas

14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 22:23

    Since Django 2.1 there is the json-script template tag. From the docs:

    json_script

    Safely outputs a Python object as JSON, wrapped in a tag, ready for use with JavaScript.

    Argument: HTML “id” of the tag.

    For example:

    {{ value|json_script:"hello-data" }} 
    

    If value is the dictionary {'hello': 'world'}, the output will be:

    
    

    The resulting data can be accessed in JavaScript like this:

    var value = JSON.parse(document.getElementById('hello-data').textContent); 
    

    XSS attacks are mitigated by escaping the characters “<”, “>” and “&”. For example if value is {'hello': 'world&'}, the output is:

     
    

    This is compatible with a strict Content Security Policy that prohibits in-page script execution. It also maintains a clean separation between passive data and executable code.

提交回复
热议问题