I want to pass a django variable which is a dictionary like this {u'testvar1': u'1', u'testvar2': u'38', u'testvar3': u'160'} to javascript.How can I do this?I cant seem to find a solution for the same.I am new to django so sorry for this noobie question.
-
1You can just pass it as a JSON objectwentjun– wentjun2019年04月29日 10:09:40 +00:00Commented Apr 29, 2019 at 10:09
4 Answers 4
First, the fact that you have strings beginning with u
means you are using Python 2.7, which is not only an extremely old version of Python but also means you are using outdated versions of Django, as more recent versions only support Python 3. You should upgrade both immediately.
To answer your question though, you should use JSON for this.
return render(request, 'my_template.html', {'data': json.dumps(data)}
and in your template:
var data = JSON.parse("{{ data|safe }}")
Comments
You pass the variables via the context and then can use them in your script in the django template
def myview():
...
return render(request, 'my_template.html', {'testvar1': testvar1}
<script>
var testvar1 = {{ testvar1 }}
</script>
1 Comment
def foo_view(request, slug):
context_data = {u'testvar1': u'1', u'testvar2': u'38', u'testvar3': u'160'}
return render(request, 'foo_template.html', context_data)
#foo_template.html
<script type="text/javascript">
var a = "{{testvar1}}";
</script>
Comments
First take that dictionary in Django template and set it to the value of one of the html elements like this:
<input type="hidden" id="dict" value="{{your dict}}">
Now take value of html element in javascript.
In java script:
<script>
var dict = document.getElementById("dict").value;
</script>