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).
- [Django]-Django Rest Framework pagination extremely slow count
- [Django]-Add a custom button to a Django application's admin page
- [Django]-Determine variable type within django template
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)
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
}
...
...
- [Django]-Django/DRF – 405 Method not allowed on DELETE operation
- [Django]-How can I chain Django's "in" and "iexact" queryset field lookups?
- [Django]-Allowing RabbitMQ-Server Connections
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.
- [Django]-Create custom buttons in admin change_form in Django
- [Django]-Why there are two process when i run python manage.py runserver
- [Django]-Itertools.groupby in a django template