Pass a list of strings from Django to Javascript

My Django objects have a City attribute. I am trying to get a list of cities and catch it in a template using Jquery (use in the diagram on the X axis).
My problem is that I cannot get rid of Unicode and quotes for a list.
(I manage to do this in a single value). Instead, I'm stuck with this:
["[[u'Paris '], [u'Lyon']]"]

I have tried many things, including JSON. No success.

My opinion: (in fact, one of many attempts ..)

def barchart1(request): city_array =[] for i in [1,MyObject.objects.count()]: objet = get_object_or_404(MyObject, pk=i) cities = [objet.city.city_name] city_array.append(cities) return render (request, 'plot3/plot_page.html', {"city_array" : city_array}) 

My JS:

 <script type="text/javascript"> var cities = ["{{ city_array }}"]; </script> 

This is how JS reads the context posted by the view
["[[u'Paris '], [u'Lyon']]"]

Here is what I would like to receive
['Paris', 'Lyon']

It MUST be something simple, but I just couldn't figure out how to do it. Other messages do not process the list of strings.

Any idea what should I do?

+7
javascript jquery django unicode
source share
1 answer

When you do {{ city_array }} in your template, your list is converted to a string. This is done by calling repr() on the list, which recursively calls repr() on its contents. Since your strings are unicode, you see these literals in unicode, u'Paris' format.

The "right" way to do this is to encode your data in json, for example, in your view:

 import json # ... json_cities = json.dumps(city_array) # ... return render (request, 'plot3/plot_page.html', {"city_array" : json_cities}) 

and then do

 var cities = {{ city_array|safe }}; 

in the template.

Please note: do not use this for user controller data! See the Xat Cheat Sheet OSWASP and the Django ticket 17419 discussion for more information. To prevent XSS, you can use something like SafeJSONEncoder from the django-cms project .

+19
source share

All Articles