8

I have a bunch of unicode strings in my data which I need to pass from my django view to template for using in a JavaScript scriptlet that passes it to the web back and forth.

The problem is I want the strings to be represented in the JavaScript unicode form but I get strings with a u prefix from python.

For example, for the string mężczyźni, Python stores 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 while processing it. I want it to be simply 'm\u0119\u017cczy\u017ani' so that the JavaScript code in the template can use it.

I tried using urqluote, smart_unicode, force_unicode but couldn't hit a solution or even a hack.

What do I do ?

3
  • Did you try escapejs Commented Aug 29, 2012 at 9:15
  • Please show your view and template code. Commented Aug 29, 2012 at 9:27
  • @BurhanKhalid, using escapejs resulted in converting the single quotes also. But that was a good hint. Thanks. Commented Aug 29, 2012 at 12:09

1 Answer 1

12

Edit: Django 1.7+ no longer includes simplejson. Instead of

from django.utils import simplejson

write

import json

and then use json instead of simplejson.


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

{{ your_python_data }}

Instead, you could export your data in json:

from django.utils import simplejson

json_data_string = simplejson.dumps(your_data)

And load the data directly in javascript:

var your_data = {{ json_data_string }};

You could also make 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 should be careful with XSS, if some of "data" comes from user input, then you should sanitize it.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @jpic That worked. I just had to add a safe filter to render it properly. So now, my code looks like this: {{ your_python_data|as_json|safe }}
Apparently, simpleJson is deprecated. Do you know what replaced it?
the native json module
On django 1.7+ simplejson is not included any more. Instead use the json - module. I will suggest an edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.