Using Django with helpers
May 7th, 2007 by viestards
Long time Django was considered as AJAX-unfriendly web framework, which does not allow JavaScript code generation. On other hand , Pylons ported Rails helpers for their framework as webhelpers.
So maybe I can use Pylons templatetags in Django? Sounds hard, because Pylons use heavy Python coding in their templates, but you underestimate power of templatetags.
To show you how to use helpers, let’s translate Pylons AJAX tutorial to Django.
To use it, you need webhelpers installed. They come with Pylons, but are available at Cheeseshop too. For JavaScript stuff, you need script.aculo.us, wihich comes with Prototype, get it here and place it in your media folder.
When everything is set, let’s start to create ping-pong site.
I assume you have Django project ready, so create a pong entry in urls.py:
(r'^pong/?$','mysite.myproject.views.pong'),
Now, somewhere in ping template put this line:
There is <a href="/pong">ping</a>
To show something, create a view. In your views.py write pong function:
def pong(request):
return HttpResponse(”There is pong!”)
This is basic page, but we need some AJAX powers. Download helpers.py code and put into templatetags folder.
In ping template page add following line at start of page:
{% load helpers %}
Change link to pong page to:
There is <a href="#" onclick="{% remote_function url:/pong/
update:pongbox %}; return false;">ping</a>
<div id=”pongbox”>
</div>
As you see, href now points at # and there is templatetag remote_function, which calls webhelpers remote_function function. Now reload page, and if everthing is right, you will see pong message below link, where pongbox is.