How to pass utf-8 data from Django to javascript
I have the following key value object in Django:
data = {
"id": 1,
"question_text": "אנא בחר אחת מהתשובות הבאות",
"answers": [
{
"label" : "תשובה 1",
"value" : 1,
"count" : 30
},
{
"label" : "תשובה 2",
"value" : 2,
"count" : 30
},
{
"label" : "תשובה 3",
"value" : 3,
"count" : 30
},
}
Note that some of the data is stored in Hebrew, so when I save it to the DB, I use:
unicode(self.answer_text).encode('utf-8')
When I tried to send this object to view to use it in Django template as well as in Javascript
I used this line:
return render(request, 'reports/report.html', {'data': data })
and in the view I used:
var question_data = {{ data }} #in order to get the data object that was sent to the view
But I am getting this item:
{'bad': 45, 'good': 55, 'question_text': u'\u05e2\u05d3 \u05db\u05de\u05d4 \u05d0\u05ea\u05d4 \u05de\u05e8\u05d5\u05e6\u05d4 \u05d0\u05d5 \u05dc\u05d0 \u05de\u05e8\u05d5\u05e6\u05d4 \u05de\u05d1\u05d2\u05d3\u05d9 \u05e2\u05dc\u05d9\u05ea \u05d1\u05d0\u05d5\u05e4\u05df \u05db\u05dc\u05dc\u05d9?', 'id': u'8', 'answers': [{'value': 30, 'label': u'\u05de\u05d0\u05d5\u05d3 \u05de\u05e8\u05d5\u05e6\u05d4'}, {'value': 25, 'label': u'\u05d3\u05d9 \u05de\u05e8\u05d5\u05e6\u05d4'}, {'value': 20, 'label': u'\u05dc\u05d0 \u05db\u05dc \u05db\u05da \u05de\u05e8\u05d5\u05e6\u05d4'}, {'value': 25, 'label': u'\u05db\u05dc\u05dc \u05dc\u05d0 \u05de\u05e8\u05d5\u05e6\u05d4'}]}
and this error in the console:
SyntaxError: Unexpected token '&'. Expected a property name
I also tried using:
var question_data = {{ data|safe }}
and I got this error:
[Error] SyntaxError: Unexpected string literal '\u05e2\u05d3 ...
I am using Django 1.7 and Python 2.7.6
Please try and help me figure out what I am doing wrong.
+3
source to share
1 answer
View
import json
# ....
return render(request, 'reports/report.html', {'data': json.dumps(data) })
Template
<script>
var question_data = JSON.parse("{{ data|escapejs }}");
console.log(question_data);
</script>
Also, you may have a syntax error in your python dict (missing closing parenthesis).
EDIT
return render(request, 'reports/report.html', {'data': data, 'data_json': json.dumps(data) })
+3
source to share