Passing unicode strings from django to javascript

I have a bunch of unicode strings in my data that I need to transfer from my django view to a template for use in a JavaScript script that transmits it back and forth to the Internet.

The problem is that strings must be in Unicode JavaScript form, but I get strings with u prefix from python.

For example, for the string mężczyźni , Python saves it as u'm \ u0119 \ u017cczy \ u017ani ' , but when it is passed to the template, it does not remove the u prefix, which creates problems for JavaScript when processing it. I want this to be just 'm \ u0119 \ u017cczy \ u017ani' so that the JavaScript code in the template can use it.

I tried using urqluote, smart_unicode, force_unicode, but could not find a solution or even hack.

What should I do?

+8
javascript python django unicode
source share
1 answer

Edit: Django 1.7+ no longer includes simplejson . Instead

from django.utils import simplejson 

records

 import json 

and then json instead of simplejson .


You are probably printing the python registry of your dict data and trying to parse it in javascript:

 {{ your_python_data }} 

Instead, you can export your data to json:

 from django.utils import simplejson json_data_string = simplejson.dumps(your_data) 

And load the data directly into javascript:

 var your_data = {{ json_data_string }}; 

You can also create a template filter :

 from django.utils import simplejson from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter def as_json(data): return mark_safe(simplejson.dumps(data)) 

And in your template:

 {% load your_template_tags %} {{ your_python_data|as_json }} 

Note that you must be careful with XSS, if some of the “data” comes from user input, then you must sanitize it.

+12
source share

All Articles