Using JSON in a django template

I have a variable containing JSON I need to go to the template. I define it as a variable and then successfully pass it to the template. However, I need a format for replacing quotes with ', but replaced with'. This causes problems with the service that I pass to this.

image_upload_params = 
{
  "auth": {
    "key": "xxx"
  },
  "template_id": "xxx",
  "redirect_url": "url-here",
}

Here's how it happens in a template:

{'redirect_url': 'url-here', 'template_id': 'xxx', 'auth': {'key': 'xxx'}}

Any idea how to make it use "instead?"

+6
source share
5 answers

Use SafeString:

from django.utils.safestring import SafeString

def view(request):
    ...
    return render(request, 'template.html', {'upload_params': SafeString(json_string)})
+14
source

zeekay, json python. json. "" django , "" .

+1

XSS, , '', , .

0

, django.

:

custom_filter.py

from django.template import Library
from django.utils.safestring import SafeString
import json

register = Library()


@register.filter("escapedict")
def escapedict(data):
    if not isinstance(data, dict):
        return data
    for key in data:
        if isinstance(data[key], int) and not isinstance(data[key], bool):
            data[key] = int(SafeString(data[key]))
        else:
            data[key] = SafeString(data[key])
    return json.dumps(data)

django

:

...
{% load custom_filter %}
some html
...
onclick="jsfunc('{{data|escapedict}}')" 
...
some html
...
...
function showdetails(data){
    parse data here
}
...
...
0

Django 2.1 json_script json_script:

Safely displays a Python object as JSON wrapped in a tag and ready for use with JavaScript

Paste this into your template:

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

It does for:

<script id="hello-data" type="application/json">{"hello": "world"}</script>

Then you can safely load this object into a JavaScript variable:

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

All Articles