Reputation: 29
I am trying to get a "json" object from a python dictionary using djnago template "json_script",which is throwing "template syntax error"
//html code
{{ value|json_script:"hello-data" }}
<script>
var Value=JSON.parse(document.getElementById("hello-data").textContent);
document.write(Value);
</script>
//views.py
from django.shortcuts import render
from django.http import HttpResponse
import random as ran
# Create your views here.
def indees(request):
vals={"123":"abc","Key":"value","hello":"user"}
return render(request,"verbat.html",context={"value":vals})
Upvotes: 1
Views: 1085
Reputation: 6921
The context is the template context dictionary, you cannot access it as a single dict, you can only access its members (keys). Read here or here for more.
E.g., In your example, you can access 'bool', 'list_' and 'msg', but probably you want to access a dictionary with these three keys.
So you need to put your data inside inner key and use it. Something like:
//views.py
def indes(request):
list_of_vals=[ran.randint(12,34),ran.randint(44,55)]
data={"bool":"True",
"list_":list_of_vals,
"msg":"hello"}
return render(request,"base.html",context={'data':data})
And inside index.html, to have:
{{ data|json_script:"hello-data" }}
Upvotes: 2