RSS Icon

Topics

View Comments

Using Django Context Variables with Javascript/Ajax

Topics: django javascript python

If you need to access Django context variables in javascript you can create a script node to store the values you want and then your scripts can access them:

<html>
<head>
<script type="text/javascript">
        var today = "{{ today }}";
    </script>
<script type="text/javascript" src="{{ MEDIA_URL }}/jquery.js"></script>
<script type="text/javascript" src="{{ MEDIA_URL }}/today.js"></script>
</head>
<body>
    Date is: <div id="date">{{ today }}</div>
<a href="#" id="yesterday">Get Yesterday</a>
</body>
</html>

Now that you can access the context variables you can make an ajax call back to have Django do more processing on the data using jQuery's post function:

// today.js
$(document).ready(function() {
    $('#yesterday').click(function() {
        $.post("/today/", {
            today: today,
            },

            function(data) {
                $('#date').html(data);
                today = data;
            }
        );
    });
});

Now all you have to do is define a view that loads the original context data and handles the async call back using the is_ajax method on the request like this:

from datetime import date, timedelta
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponse
from datetime import datetime
from dateutil import parser

DATE_FORMAT='%m/%d/%Y'

def today(request, template='core/today.html'):
    if request.is_ajax():
        t = request.POST.get('today')
        dt = parser.parse(t)
        one_day = timedelta(days=1)
        yesterday = dt - one_day

        return HttpResponse(yesterday.strftime(DATE_FORMAT))
    else:
        today = date.today()
        return render_to_response(template, {'today': today.strftime(DATE_FORMAT)},
                context_instance=RequestContext(request))

This is a very basic example of how to access Django's context variables and using ajax with Django but it should now be obvious how easy it is to do more complex things with it.

View Comments

Don't host jQuery yourself, use Google!

Topics: javascript jquery

Google has a content delivery network (CDN) dedicated to serving the most popular open source JavaScript libraries here. This will give you faster delivery and better caching for your clients. The Google CDN chooses the best server to provide the library from based on the client location.

Along with location based delivery it also gives you the benefit of saving load on your server and delivering more of your local content faster. Most popular browsers limit the amount of connections from a server that can be made for downloading content and by pushing off your JavaScript loading onto Google’s servers you are freeing up connections that can be used for the rest of your application.

Currently Google hosts jQuery, Prototype, script.aculo.us, MooTools, Dojo, SWFObject, YUI, and Ext.