views:

805

answers:

5

I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, but how do I embed the data object in that script (on the fly) so the script's functions can use it?

Put another way, I want to create a JavaScript object or array from a Python dictionary, then insert that object into the JavaScript code, and then insert that JavaScript code into the HTML.

I suppose this structure (e.g., data embedded in variables in the JavaScript code) is suboptimal, but as a newbie I don't know the alternatives. I've seen write-ups of Django serialization functions, but these don't help me until I can get the data into my JavaScript code in the first place.

I'm not (yet) using a JavaScript library like jQuery.

+2  A: 

It is suboptimal. Have you considered passing your data as JSON using django's built in serializer for that?

Paul McMillan
I thought I'd learn some basics before wading into the acronyms. But it seems I can either learn some JSON, or build a solution from basic elements, which I'll scrap once I've learned some JSON.
chernevik
+3  A: 

You can include <script> tags inside your .html templates, and then build your data structures however is convenient for you. The template language isn't only for HTML, it can also do Javascript object literals.

And Paul is right: it might be best to use a json module to create a JSON string, then insert that string into the template. That will handle the quoting issues best, and deal with deep structures with ease.

Ned Batchelder
+5  A: 

I recommend against putting much JavaScript in your Django templates - it tends to be hard to write and debug, particularly as your project expands. Instead, try writing all of your JavaScript in a separate script file which your template loads and simply including just a JSON data object in the template. This allows you to do things like run your entire JavaScript app through something like JSLint, minify it, etc. and you can test it with a static HTML file without any dependencies on your Django app. Using a library like simplejson also saves you the time spent writing tedious serialization code.

If you aren't assuming that you're building an AJAX app this might simply be done like this:

In the view:

from django.utils import simplejson


def view(request, …):
    js_data = simplejson.dumps(my_dict)
    …
    render_template_to_response("my_template.html", {"my_data": js_data, …})

In the template:

<script type="text/javascript">
    data_from_django = {{ my_data }};
    widget.init(data_from_django);
</script>

As far as dates go, you might also want to think about how you pass dates around. I've almost always found it easiest to pass them as Unix timestamps:

In Django:

time_t = time.mktime(my_date.timetuple())

In JavaScript, assuming you've done something like my_date = {{ time_t }} with the results of the snippet above:

my_date = new Date();
my_date.setTime(time_t);

Finally, pay attention to UTC - you'll want to have the Python and Django date functions exchange data in UTC to avoid embarrassing shifts from the user's local time.

Chris Adams
Thanks. I planned to serve the javascript as a media file, similar to a css stylesheet. This seems like a better solution than embedding the data in the js, though I'll have to learn some JSON, and write some server-side code to handle data requests.
chernevik
Sounds like a good idea - one thing which I really like about that approach is that it's trivial to write a Django view which returns JSON (if you do this often, look at django-piston for creating REST APIs) and it's very easy to test isolated parts that way.
Chris Adams
I'm not ignoring this! I'm just building up my knowledge of writing and serving javascript to the point where I actually use it. I'm now planning to use JSON to pass in metadata to drive which widgets are affected by the menu choice, but this has required me learning more about creating and accessing javascript data structures.
chernevik
I got this approach to work, and tried to select it as the answer -- and was told it was too old to be changed, unless it was edited! Mea culpa. If you edit this, I'll select it as the answer.
chernevik
Ah, updated. Thanks!
Chris Adams
Note for people searching the archives: if you need to pass dates directly to a JSON consumer which uses strict ISO8601 dates, you might find this bit of code from a recent YUI app helpful: http://www.djangosnippets.org/snippets/1841/
Chris Adams
A: 

See the related response to this question. One option is to use jsonpickle to serialize between Python objects and JSON/Javascript objects. It wraps simplejson and handles things that are typically not accepted by simplejson.

John Paulett
A: 

Putting Java Script embedded into Django template is rather always bad idea.

Rather, because there are some exceptions from this rule.

Everything depends on the your Java Script code site and functionality.

It is better to have seperately static files, like JS, but the problem is that every seperate file needs another connect/GET/request/response mechanism. Sometimes for small one, two liners code os JS to put this into template, bun then use django templatetags mechanism - you can use is in other templates ;)

About objects - the same. If your site has AJAX construction/web2.0 like favour - you can achieve very good effect putting some count/math operation onto client side. If objects are small - embedded into template, if large - response them in another connection to avoid hangind page for user.

bluszcz
Yes, and you have builtin json into django ;) Forget about xml :P
bluszcz