April 7th, 2013

Easy as pie Ajax with Django and Bootstrap

Tutorial for: bootstrap-ajax


Need a quick and effortless way to Ajax enable your Django and Bootstrap website? Look no further than bootstrap-ajax.

I recently tried bootstrap-ajax with my Uarica: Idea Collaboration website. It is used to perform Likes, Follows, and comment removal on the website by end-users. And it works wonderfully and was super easy to implement. This tutorial will be rather short, as it is just that easy to use this Bootstrap, from Twitter add-on.

{% with likes=idea.likes.all %}
<a class="btn ajax" data-replace-closest="a" href="{% url 'like-idea' idea.owner.username idea.slug %}">{{likes|length}}<i class="{% if user in likes %}icon-star{% else %}icon-star-empty{% endif %}"></i></a>
{% endwith %}

This is source code from my Uarica website to generate the like button, the part which makes the Ajax magic work is the ajax class, and the data-replace-closest attribute. When the button is clicked, it uses the URL in the href, and the data that comes back is replaced in the closest A tag, which in this case is the link the user just clicked.

def like_idea(req, username, slug):
    # Source goes here to add/remove the like.
   return HttpResponse(json.dumps({'hml':link, 'fragments':{'#ajax_message':msg}}), mimetype='application/json')

Since my website is not open sourced, I am limited on what I can actually display here. However the logic to determine a like and add/remove it should be evident. What I want to focus on with this snippet is not the like system, but how to return a JSON response, so that the bootstrap ajax toolkit can use it. The fragment keyword is optional, it is used here to return back an AJAX message to inform the user of their recent action. The keyword you want to return back is html, this is what will be replaced on the HTML page. In the case of this example, the A tag will be replaced by what is in the link variable. Easy as pie to use, isn't it? Best of all, the example application for this bootstrap library is Django! You can check it out on their website here: http://uk013.o1.gondor.io/.

There are so many methods of developing AJAX applications in Django, to see the other ones check out the tutorial section.

About Me

My Photo
Names Kevin, hugely into UNIX technologies, not just Linux. I've dabbled with the demons, played with the Sun, and now with the Penguins.

Kevin Veroneau Consulting Services
Do you require the services of a Django contractor? Do you need both a website and hosting services? Perhaps I can help.

This Month

If you like what you read, please consider donating to help with hosting costs, and to fund future books to review.

Python Powered | © 2012-2019 Kevin Veroneau