Ajax with Django and jQuery
A current software project of mine is hosted on Django, and I’ve been working on a front-end interface.
Django itself is a pleasure to work with, as I keep discovering cool little benefits it offers, shortcuts, ways to do things quickly, and well. I especially like how well it encourages the DRY (Don’t Repeat Yourself) principle. I keep the main javascript code in a specific file, code.html, and simply use a {%ssi “code.html”%} on any page I need the big chunk of javascript.
I’ve been using galleria and jCarousel in conjunction, a few small problems, which when I solve them, I’ll detail here.
I did have a lot of fun working with the ajax, getting it working, and here’s what I did.
I created a view, called next_image:
def next_image(request, series_name, issue_name, panel_number):
name = urllib.unquote(series_name)
ish_name = urllib.unquote(issue_name)
series = Series.objects.get(ser_title=name)
issue=series.issue_set.get(ish_title=ish_name)
pages = issue.page_set.get(page_number=int(panel_number)+1)
i='<img title="'+str(int(panel_number)+1)+" \
src="http://oddco.ca/zerothsblog/wp-admin/'+p+'" alt="" />'
return HttpResponse(i, mimetype="text/html")
I just take the safe html versions of the variables passed to me, use urllib.unquote to get the actual symbols(ie, going from %3E to >), do a few searches, and find the specific page needed. I’m sure there are much more efficient ways to do this, with only one sql-alike statement, but I don’t know how yet.
Basically, all I return is a simple img tag, which is then handled on the other end by the following javascript:
jQuery.get('/ajax/next-image/{{series_name}}/{{issue_name}}/'+endMarker+'/', function(data){
carousel.add(carousel.last+1, data);
carousel.size(carousel.size()+1);
Which reminds me, I hate how badly wordpress handles code snippets. Its the most atrocious tag handling I’ve ever seen, so if the code looks ugly, or whatever, blame wordpress.
Onto the code. We do a basic get command, which uses django template variables to replace the sections with {{ and }} with the appropriate variable. Then, add a function for the callback, to handle the data when it comes back. In the callback, we add the data to the carousel, and then extend the size of the carousel by one.
However, this code has one major bug, which I have not solved yet: galleria support. It seems that Galleria is only partially hooking into the new images, where the hotkeys work, but not actually clicking on the images. If anyone has any solutions or advice, give me a shout! I’d gladly appreciate the help.