Using Django Context Variables with Javascript/Ajax

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>

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.