Simeon Franklin

Blog :: AHAH with Django and jQuery

22 August 2011

I was recently asked about using AJAX via jQuery with Django and mentioned that I frequently use html fragments and a decorator to add Ajax functionality to existing views. Let's see how that works.

I have an existing view that I want to refresh via AJAX. Let's make the simplest thing possible:


from django.shortcuts import render_to_response
from django.template import RequestContext

counter = [0]

def index(request):
    counter[0] = counter[0] + 1
    return render_to_response("index.html",
                              {'counter': str(counter[0])},
                        context_instance=RequestContext(request))

My views function renders a template and increments a constant each time the view is loaded. I know, I know, my counter is reset if my server restarts and I'm not thread safe but hey - this is just an example! The view is rendered by two templates:

index.html

{% extends "base.html" %}
{% block mytext %}
Current counter value is {{ counter }}.
{% endblock %}

and base.html

<html>
  <head>
    <title>Simple Demo</title>
  </head>
  <body>
  <h1>This is a simple page</h1>
  <div id="replace_me">
    {% block mytext %}
    This is dynamic content that should be replaced.
    {% endblock %}
  </div>
  </body>
</html>  

Each time I reload the page I see something like:

This is a simple page

Current counter value is 2.

We've got our initial case setup, lets make it AJAX! No, on second thought lets make it AHAH! AJAX technically stands for Asynchronous Javascript And XML but I rarely find myself using XML lately. If I actually need a data interchange format I usually use JSON - but I also frequently find myself using the Asynchronous Javascript and HTML pattern instead. I guess that comes out to AJAH but AHAH is definitely more fun to say.

The technique is very simple - the part of my page that needs to be loaded Asyncronously can be managed by just loading a snippet of HTML and inserting it instead of exchanging data and using Javascript to rebuild the page. This is usually less code (especially Javascript) and has the advantage of using the same views on the server side and hopefully the same templates. It's also built into my favorite Javascript Framework - so lets see it in action.

First I'm going to add the jQuery library to my base template and the JS and html necessary to trigger the asyncronous reloading. Now my template looks like:


<html>
  <head>
    <title>Simple Demo</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
      $(function(){
          $("#click_me").click(function(){
              $("#replace_me").load("/ #replace_me");
          });
      });
  </script>
  </head>
  <body>
  <h1>This is a simple page</h1>
  <div id="replace_me">
    <div>
    {% block mytext %}
    This is dynamic content that should be replaced.
    {% endblock %}
    </div>
  </div>
  <a id="click_me" href="#">Click Me</a>
  </body>
</html>  

I'm not going to explain the javascript in detail - but even inexperienced jQueryists can see that I added a function triggered by clicking my link and the function uses jQuery's built in .load() function to make an asyncronous call to the url "/". I also specify a CSS selector so the loaded page (which is equivalent to refreshing the current page) is parsed and the contents of the first div inside of #replace_me are inserted into the current page's #replace_me div. My number changes without a browser reload! Woohoo!

But lets make this better and slightly more complicated. Maybe we don't want to render the whole page each time because our base template does complicated things like showing the logged in user, building a menu, constructing a recent changes sidebar and so on. We'd like each Asyncronous call to only build the piece of dynamic data that's changing.

To do this we can take advantage of a utility method on the Django request object called .is_ajax(). This depends in turn on using a sane browser or Javascript framework but in our case jQuery makes sure that a "X-REQUESTED-WITH" header is sent with each asyncronous request. The view code now reads:


from django.shortcuts import render_to_response
from django.template import RequestContext

counter = [0]

def index(request):
    counter[0] = counter[0] + 1
    if request.is_ajax():
        template = "index_ajax.html"
    else:
        template = "index.html"
    return render_to_response(template,
                              {'counter': str(counter[0])},
                        context_instance=RequestContext(request))

My new index_ajax.html template has just the fragment we're interested in and my old index.html has been modified to include it:

index_ajax.html

Current counter value is {{ counter }}.

and index.html

{% extends "base.html" %}
{% block mytext %}
{% include "index_ajax.html" %}
{% endblock %}

I also alter the base.html template to drop the css selector in my .load() call. Looking at the requests in firebug confirms that only the piece of text I want is included each time but the page works as before - the first time the page loads normally and clicking the link fires an asyncronous call that returns only fragment we want and inserts it into the parent page.

base.html

<html>
  <head>
    <title>Simple Demo</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
      $(function(){
          $("#click_me").click(function(){
              $("#replace_me").load("/");
          });
      });
  </script>
  </head>
  <body>
  <h1>This is a simple page</h1>
  <div id="replace_me">
    {% block mytext %}
    This is dynamic content that should be replaced.
    {% endblock %}
  </div>
  <a id="click_me" href="#">Click Me</a>
  </body>
</html>  

Things now work as I want but we can still clean up our code a bit. I usually use the decorator from django-annoying to give myself a nice render_to shortcut. You can read the code to see how it works but using it is simple - either specify your template in the call to the render_to decorator or return it in the "TEMPLATE" key in the dict that your view returns - render_to will handle generating a request_context and rendering your template for you. Now my view looks like (with the linked decorator copied to decorators.py next to my views.py):


from django.shortcuts import render_to_response
from django.template import RequestContext
from decorators import render_to

counter = [0]

@render_to()
def index(request):
    counter[0] = counter[0] + 1
    if request.is_ajax():
        template = "index_ajax.html"
    else:
        template = "index.html"
    return {'TEMPLATE': template, 'counter': str(counter[0])}

much nicer and everything works as before. This is such a common pattern for me, however, that I put the template picking logic in the decorator itself right after it pops the TEMPLATE variable:


    tmpl = output.pop('TEMPLATE', template)
    if request.is_ajax():
        if "AJAX_TEMPLATE" in output:
            tmpl = output.pop("AJAX_TEMPLATE")

This allows me to just specify my two templates in my returned dict and the right one will automatically be picked. One last time for views.py:


from django.shortcuts import render_to_response
from django.template import RequestContext
from decorators import render_to

counter = [0]

@render_to()
def index(request):
    counter[0] = counter[0] + 1
    return {'TEMPLATE': 'index.html',
            'AJAX_TEMPLATE': 'index_ajax.html',
            'counter': str(counter[0])}

And we're done. A single line of Javascript (more or less) enables our Asyncronous call and at the price of one more template we can alternately render fragments or the whole page for our view with the decorator cleaning up our view code and handling the template choosing for us.


blog comments powered by Disqus