[Django]-Using JSON in django template

21👍

Use SafeString:

from django.utils.safestring import SafeString

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

38👍

Django 2.1 added the json_script template filter:

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

Insert this in your template:

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

It renders to:

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

Then, you can safely load this object in a JavaScript variable:

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

This approach is safer than simply writing var value = {{value|safe}}; because it protects you from XSS attacks (more in this ticket).

1👍

I found a method which uses a django custom template filter.

The filter code looks like this

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 document

And in the template, we use the filter like this:

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

0👍

As zeekay mentioned, just use the python built-in json library. It will automatically output valid json data. You’ll still have to mark it “safe” for django to use in templates but you can do that using the “safe” template filter.

Leave a comment