Reputation: 455
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
// <testsite.views.data object at 0x1045f1e48>
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
// {"item_1": 123, "item_2": 456, "item_3": ["a","b","c",]
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?
Upvotes: 1
Views: 5119
Reputation: 10421
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 "
Upvotes: 6