19👍
As mentioned, you could use the |safe
filter so Django doesn’t sanitize the array and leaves it as is.
Another option, and probably the better one for the long term is to use the simplejson
module (it’s included with django) to format your Python list into a JSON object in which you can spit back to the Javascript. You can loop through the JSON object just like you would any array really.
from django.utils import simplejson
list = [1,2,3,'String1']
json_list = simplejson.dumps(list)
render_to_response(template_name, {'json_list': json_list})
And in your Javascript, just {{ json_list }}
- [Django]-Save() prohibited to prevent data loss due to unsaved related object
- [Django]-How to get primary keys of objects created using django bulk_create
- [Django]-Remove duplicates in a Django query
7👍
In Django:
from django.utils import simplejson
json_list = simplejson.dumps(YOUR_LIST)
AND PASS “json_list” IN CONTEXT
IN JS:
var YOUR_JS_LIST = {{YOUR_LIST|safe}};
- [Django]-How can I set a default value for a field in a Django model?
- [Django]-Django models.py Circular Foreign Key
- [Django]-Django south migration – Adding FULLTEXT indexes
0👍
It could be done by django core serializers. All you need to do is to serialize your data in json and than pass it to template.
data = serializers.serialize("json", <list>)
return render(request, 'view.html', {'data':data})
In your template save this list into javascript variable.
var list = {{data|safe}}
- [Django]-Creating a JSON response using Django and Python
- [Django]-How do I get user IP address in Django?
- [Django]-How to perform OR condition in django queryset?
0👍
- [Django]-Use get_queryset() method or set queryset variable?
- [Django]-'EntryPoints' object has no attribute 'get' – Digital ocean
- [Django]-Django order_by() filter with distinct()
0👍
Not sure when it was added to Django, a candate for the same result is json-script:
{{ value|json_script:"hello-data" }}
If value is the dictionary {‘hello’: ‘world’}, the output will be:
<script id="hello-data" type="application/json">{"hello": "world"}</script>
The resulting data can be accessed in JavaScript like this:
const value = JSON.parse(document.getElementById('hello-data').textContent);
ID, "hello-data" in the case above will be optional on Django versions after 4.0.
- [Django]-How to check whether the user is anonymous or not in Django?
- [Django]-How to annotate Count with a condition in a Django queryset
- [Django]-Django: Get current user in model save