'Passing a Dictionary from Django view to a Django template
I am trying to pass the following context from views.py to a Django Template:
views.py:
def home(request):
context = {
'dict_1': {'key_1': ['val_11', 'val_12'], 'key_2': ['val_21', 'val_22']}
}
return render(request, 'app/home.html', context)
home.html:
<script type="text/javascript">
var java_dict = {{ dict_1 }};
console.log(java_dict);
</script>
This throws an error: Uncaught SyntaxError: Unexpected token '&'
Upon investigating, I see that the dictionary in javascript is read as follows:
{'key_1': ['val_11', 'val_12'], 'key_2': ['val_21', 'val_22']}
which probably means that the quotes-character (') is read incorrectly. How do I fix this issue?
Solution 1:[1]
The context data that you pass into Django templates are escaped by default, for security purposes.
If you're sure that the data is safe, you can do this:
views.py
import json
def home(request):
# Use JSON dump so that it will be a data that can be loaded in javascript
context = {
'dict_1': json.dumps({
'key_1': ['val_11', 'val_12'], 'key_2': ['val_21', 'val_22']
})
}
return render(request, 'app/home.html', context)
home.html
<script type="text/javascript">
var java_dict = {{ dict_1| safe }}; // Actually solve your problem. Don't escape the data.
console.log(java_dict);
</script>
Solution 2:[2]
By default, all values in Django templates escape HTML characters for security purposes. If you want to use this dictionary in JavaScript you should use json_script filter. Please read the docs to understand what's going on.
A solution for your problem would be to:
Add the script tag containing your dict to the template
{{ dict_1 |json_script:"ID_OF_NEW_SCRIPT_TAG" }}Load the dict value in your script tag (I'll use the name you had in your example)
var java_dict = JSON.parse(document.getElementById('ID_OF_NEW_SCRIPT_TAG').textContent); console.log(java_dict);
Replace ID_OF_NEW_SCRIPT_TAG with whatever ID makes sense to you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Meng Kiat |
| Solution 2 | koressi |
