Twitter user timeline with a Django templatetag

By Nuno Mariz, on 11 February 2008 @ 10:45
A simple templatetag for adding to the template context a variable with the user timeline from Twitter.
It uses the CachedContextUpdatingNode snippet for caching from Jacob Kaplan-Moss.
The reason that is necessary to cache content is because Twitter limits the number of accesses to the API.
This only works if the cache is enabled on your
class TwitterNode(CachedContextUpdatingNode):

    cache_timeout = 1800 # 30 Minutes, maybe you want to change this
    def __init__(self, username, varname):
        self.username = username
        self.varname = varname

    def make_datetime(self, created_at):
        return datetime.fromtimestamp(mktime(strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y')))

    def get_cache_key(self, context):
        return 'twitter_user_timeline_cache'

    def get_content(self, context):
            response = urllib.urlopen('' % self.username).read()
            json = simplejson.loads(response)
            return {self.varname : None}
        for i in range(len(json)):
            json[i]['created_at'] = self.make_datetime(json[i]['created_at'])
        return {self.varname : json}
def twitter_user_timeline(parser, token):
    bits = token.contents.split()
    if len(bits) != 4:
        raise TemplateSyntaxError, "twitter_user_timeline tag takes exactly three arguments"
    if bits[2] != 'as':
        raise TemplateSyntaxError, "second argument to twitter_user_timeline tag must be 'as'"
    return TwitterNode(bits[1], bits[3])
{% twitter_user_timeline username as twitter_entries %}
{% if twitter_entries %}
  {% for entry in twitter_entries %}
  {{ entry.created_at|date:"d M Y H:i" }} - {{ entry.text }}
  {% endfor %}
{% endif %}
Use the source, Luke.


  • #1 By Pedro on 20 October 2010 @ 16:21
    Me again. After adding all the imports it worked great. These lines have to be first to make it work:
    from template_cache import CachedContextUpdatingNode
    from django.template import Library, Node
    from django.utils import simplejson
    from datetime import datetime
    from time import mktime, strptime
    import urllib
    [NOTE: `template_cache` is the snippet mentioned above made by some guy called Jacob :P]

    I also added an extra argument: an integer before the username to be able to set how many twits we want to get.
    {% twitter_user_timeline 3 pedromagnus as twitter_entries %}
    this would get the last 3 twits from pedromagnus twitter.

  • #2 By chris on 4 January 2011 @ 01:32
    The caching doesn't seem to be doing for some reason. Copied source and am using the template tag, but my database isn't being filled and there is no error.
Comments are closed.