1

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.

asked Apr 29, 2019 at 10:05
1
  • 1
    You can just pass it as a JSON object Commented Apr 29, 2019 at 10:09

4 Answers 4

2

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 }}")
answered Apr 29, 2019 at 10:42
Sign up to request clarification or add additional context in comments.

Comments

0

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>
answered Apr 29, 2019 at 10:10

1 Comment

I have tried this but the javascript variable testvar1 becomes a string.I want to store my django variable in form of json in javascript
0
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>
answered Apr 29, 2019 at 10:10

Comments

0

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>
answered Apr 29, 2019 at 12:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.