Kane
Kane

Reputation: 176

Retrieving json objects from python (using Django) - Javascript

I have been poking around the web but have not been able to find an example which works for me. It seems as though it is a simple mistake as I have seen multiple examples that are very similar, but when I try following these I keep getting errors (mainly SyntaxError: invalid property id).

Python code (in Django view):

my_dict = {'mykey' : 'myvar'}
jtest = json.dumps(my_dict)
context = {'form': form, 'test_dict' : jtest}

return render(request, "browsefiles.html", context)

Javascript:

<script type="text/javascript">
  var data = {{ test_dict }};
</script>

Error:

SyntaxError: invalid property id

If someone could help me find what is causing this error that would be greatly appreciated. I would like to access the dictionary in the in the javascript code segment.

Upvotes: 0

Views: 260

Answers (1)

nima
nima

Reputation: 6733

Django will escape special characters in your page and the browser cannot recognize the object. You must mark it as safe for Django to leave it alone:

<script type="text/javascript">
  var data = {{ test_dict|safe }};
</script>

Upvotes: 2

Related Questions