user1852176 user1852176 - 21 days ago 12
Javascript Question

Accessing dict values in Django template

Edit - The issue has been solved

The problem was solved and I would appreciate it if someone would upvote this post so it doesn't appear to others that it's a waste of time. A user gave an answer that I didn't accept because it didn't work, but he insisted his response was correct and argued anyway. I had to slightly modify the accepted answer (which I commented how) and solved the problem. Hope this helps someone in the future.

I'm having trouble accessing the values of a dict object that I'm trying to send to a template in Django. I can access and print the dict's contents in my view, but when I try to send the data to my template there are all kinds of characters like it isn't encoded properly. At first I thought it might have been an issue with serializing, but I found this post which states that json_serializer.serialize is supposed to be used with a queryset. Is this correct? From here I tried the following.

At first I tried to just send the data variable by itself without any formatting like so

data = {'item_1': 123, 'item_2': 456, 'item_3': ['a','b','c'] }
return render(request, 'testsite/new_page.html', {'data' : data} )


In the template I have the following

<script>var data = "{{ data }}"; </script>
<script>console.log(data);</script>

// displays the following
// &lt;testsite.views.data object at 0x1045f1e48&gt;


Then I tried to format the data to JSON

data = {'item_1': 123, 'item_2': 456, 'item_3': ['a','b','c'] }
return render(request, 'testsite/new_page.html', {'data' : json.dumps(data.__dict__) } )

//template
<script>var data = "{{ data }}"; </script>
<script>console.log(data);</script>

// the following is the improperly formatted result
// {&quot;item_1&quot;: 123, &quot;item_2&quot;: 456, &quot;item_3&quot;: [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,]


If I don't use
json.dumps(data.__dict__)
and instead just have
json.dumps(data)
I get an error about the object is not JSON serializable

In my view I have the following. The contents of the dict are properly formatted.

print(data.__dict__)
import pdb; pdb.set_trace()

# displays the dict properly
# {'item_1': 123, 'item_2': 456, 'item_3': ['a','b','c'] }


In the template tried to iterate through the data object using javascript like so, but it just displays each individual character of the improperly formatted dict.

for (var key in data) {
console.log(data[key]);
}


What am I doing wrong that is causing the improperly formatted data in the template?

Answer

consider using

return render(request, 'testsite/new_page.html', {'serialized_data' :json.dumps(data) } )

with

<script>var data = "{{ serialized_data | safe }}"; </script>

Note the safe filter there stops django to turn your " into &quot;

Comments