Tumblelog

This is how to create a tumblelog with Django. It consist of display chrnologicaly the last things that happened on your blog : articles, photos, music, every thing you desire !

The mechanism is based on Django’s content types, we are going to associate a generic object call LogItem with an other object less generic like a article (Post) or a photo (Photo) for example.

Here, we are only going to display the latest articles and photos created.

Models

The LogItem object is a simple and generic object that point to an article or a photo. See for yourself :

It easy to understand that if we have the class and the id of the linked object, we can easily instanciate it. This is what our get_content_object method is here to do :

def get_content_object(self): from django.core.exceptions import ObjectDoesNotExist try: return self.content_type.get_object_for_this_type(pk=self.object_id) except ObjectDoesNotExist: return None

You will need to change the delete method of the object you link to delete the LogItem that are associated to them :

def delete(self): from cyberdelia.tumblelog.models import LogItem try: log = LogItem.objects.get(object_id=self.id, content_type=ContentType.objects.get_for_model(self)) log.delete() except LogItem.DoesNotExist: pass super(Post, self).delete()

Download the models.

Views

Nothing to complicated here, a simple generic view to display the latest 15 elements, for the details see the recommendations tutorial.

Download the urls.py.

Templates

The template receive a list of LogItem object call object_list, we just need to display them now. To find out the type of the object, we juste need to make a comparison :

{% ifequal item.content_type.name "post" %}

Then, we just need to display the specific informatiosn for the article or the photo associated. We access to the object via the get_content_object method.

Download the template.

And now ?!

We just need to feed the monster with fresh data ! We can’t update data at each load of the page, that will cost you a lot of ressources and will be pretty much useless, we are jsut going to use a goold old script that cron with launch every 15 minutes…

Our cron configuration will look like that (if you want to launch it every 15 minutes) :

*/15 * * * * www-data python /var/www/cyberdelia/tumblelog/bin/update.py --settings="cyberdelia.settings"

This script will serach for last articles and photos published and will create LogItem that link to them if they didn’t already exists.

Download this script.