storing django object into javascript array

4,422 views
Skip to first unread message

jay K.

unread,
Jun 10, 2011, 10:48:30 AM6/10/11
to Django users

Hello,

I am not a django developer, but I have a background on html, css,
javascript, jquery and php.

I was wondering if you can help me with a question regarding django,
since I'm working on a website built on django (which was not started
by me)

I want to store a django object into a javascript array. So far I have
this code:

In my template file:

<script type="text/javascript" language="javascript" charset="utf-8">

var map_schools = {{ city.school_set.all }};

</script>

Unfortunately the django object is not stored as desired, but instead
it gets stored like the following:

var map_schools = [&lt;School: Oxford, Eckersley&gt;]

I am unable to work with the javascript array. Right now this piece of
code is commented out because enabling it prevents the rest of the js
code from running properly

Any suggestions are welcome

Thanks,

Regards,

Brice Leroy

unread,
Jun 10, 2011, 12:17:54 PM6/10/11
to django...@googlegroups.com
Hello Jay,

When you call  city.school_set.all ,you get an array of object. the template render the string representation of the object.

You might want to loop other them. Check the json serializer too : 


Brice
2011/6/10 jay K. <jay.deve...@gmail.com>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.




--
blog: http://www.debrice.com
Time tracking tool: http://alpha.kaaloo.com 

Ian Clelland

unread,
Jun 10, 2011, 12:21:33 PM6/10/11
to django...@googlegroups.com
On Fri, Jun 10, 2011 at 7:48 AM, jay K. <jay.deve...@gmail.com> wrote:

Hello,

I am not a django developer, but I have a background on html, css,
javascript, jquery and php.

I was wondering if you can help me with a question regarding django,
since I'm working on a website built on django (which was not started
by me)

I want to store a django object into a javascript array. So far I have
this code:

In my template file:

<script type="text/javascript" language="javascript" charset="utf-8">

var map_schools = {{ city.school_set.all }};

</script>

Unfortunately the django object is not stored as desired, but instead
it gets stored like the following:

var map_schools = [&lt;School: Oxford, Eckersley&gt;]


[<School: Oxford, Eckersley>] is the printable representation of your query set (what you get when you call city.school_set.all()) -- what you need to do is build up a JavaScript literal that you can insert into the code. There are two fairly simple ways of doing this:

1. Use a loop in the template:

var map_schools = [{% for school in city.school_set.all %}"{{ school|escapejs }}"{% if not forloop.last %},{% endif %}{% endfor %}];

You'll notice a couple of things there:
  - there is a "for" loop there, to iterate over all of the schools in the result set
  - the quotes are present in the template, to make sure that the school names are strings in the JavaScript
  - there is a test after every string to see if a "," is needed as a separator (some javascript implementations are not very forgiving if you put a comma after the last element)
  - Every school name is passed through the "escapejs" filter, to avoid breaking out of the string.

2. Construct a JSON string in python:

In your view, do something like this:

    from django.utils.simplejson import dumps
    ...
    school_list = dumps([school.name for school in city.school_set.all()])

and then add school_list to the context variables that are passed to the template. Then in the template, you can just use {{ school_list }}, and it will be a properly formatted JavaScript array.



--
Regards,
Ian Clelland
<clel...@gmail.com>

jay K.

unread,
Jun 14, 2011, 4:03:46 PM6/14/11
to django...@googlegroups.com
Hello,

I was given the following solution for storing a django object in a javascript variable

//SOLUTION BEGINS HERE
1. Use a loop in the template:

var map_schools = [{% for school in city.school_set.all %}"{{ school|escapejs }}"{% if not forloop.last %},{% endif %}{% endfor %}];

You'll notice a couple of things there:
  - there is a "for" loop there, to iterate over all of the schools in the result set
  - the quotes are present in the template, to make sure that the school names are strings in the JavaScript
  - there is a test after every string to see if a "," is needed as a separator (some javascript implementations are not very forgiving if you put a comma after the last element)
  - Every school name is passed through the "escapejs" filter, to avoid breaking out of the string.

//SOLUTION ENDS

Now, I was wondering how I can store the {{ school|escapejs }} into a javascript array, and use the data inside school as if it were an array element, like map_schools[1], map_schools[3] etc

Thanks

regards,

JK


jay K.

unread,
Jun 14, 2011, 6:43:27 PM6/14/11
to Django users

Hello,

I've posted my question before, but I believe I didn't provide enough
detail. I intend to present my issue again, this time with more
detail.

Let me tell you that I am not a django developer, so I have very
limited exposure to django. I just know html, css, javascript, jquery,
php (also java and c++, so I'm familiar with object-oriented
programming).

I have a website which let's the user choose different cities. In each
city there are several language schools, and each of the schools have
got a name and a set of coordinates (these coordinates will be used to
mark the school on google map)

The relevant bits of the School model look like this:

//BEGINNING

class School(models.Model):
....
name = models.CharField(max_length = CHARFIELD_NORMAL_LENGTH)
....

map_latitude = models.CharField(blank = True, null = False,
max_length=255, help_text = "Latitude")
map_longitude = models.CharField(blank = True, null = False,
max_length=255, help_text = "Longitude")

....
//END

To retrieve the data from the django admin into my "City" template
(where all schools from a particular city are displayed) I have the
following code

//BEGINNING
<script type="text/javascript">
....
var city_schools = [{% for school in city.school_set.all
%}"{{ school.name|escapejs }}"{% if not forloop.last %},{% endif %}{%
endfor %}];

var city_latitudes = [{% for school in city.school_set.all
%}"{{ school.map_latitude|escapejs }}"{% if not forloop.last %},{%
endif %}{% endfor %}];

var city_longitudes = [{% for school in city.school_set.all
%}"{{ school.map_longitude|escapejs }}"{% if not forloop.last %},{%
endif %}{% endfor %}];
....
</script>
//END


Now, I manage to see the output of the javascript written above
through Firefox's "View - Page Source" and it comes up like this

//BEGINNING
var city_schools = ["EC","St. Giles Central","St. Giles Highgate"];

var city_latitudes = ["58","88","25"];

var city_longtitudes = ["7","99","100"];

//END


I have a separate javascript file where I add the code for the google
map. What I want to do is to be able to access each of the
city_schools, city_latitudes, and city_longitudes and use its data to
I can mark the schools inside a google map. It would be ideal if I
could retrieve the info as if it was a js array, but any method that
works is more than welcome

Or better, if you can show me how to mark the schools on the google
map more efficiently it would be great

Thanks,

Regards,

Jay K.

John Finlay

unread,
Jun 15, 2011, 1:33:08 PM6/15/11
to django...@googlegroups.com
How about something like:

<script type="text/javascript">
....
var city_schools = [{% for school in city.school_set.all %}

{ "school" : "{{ school.name }}",
"latitude" : "{{ school.map_latitude }}",
"longitude" : "{{ school.map_longitude }}"
},


{% endfor %}
]
....
</script>

John

Reply all
Reply to author
Forward
0 new messages