Django Tutorial - Video 14 - Reverse URLs

This tutorial covers instantiating an instance of the Python-Twitter api, Authenticating to Twitter, and how to get and post tweets from the Twitter Api.


Python twitter can be downloaded from http://code.google.com/p/python-twitter/

pages/views.py

from django.shortcuts import render_to_response
from django.template import RequestContext
from pages.models import HomePage

def MainHomePage(request):
        homepage = HomePage.objects.get(pk=1)
        context = {'homepage': homepage, 'tweets': getTweets()}
        return render_to_response('index.html', context, context_instance=RequestContext(request))

''' INTERNAL FUNCTION - not called from a URL '''
def getTweets():
        tweets = []
        try:
                import twitter
                api = twitter.Api()
                latest = api.GetUserTimeline('HackedExistence')
                for tweet in latest:
                        status = tweet.text
                        tweet_date = tweet.relative_created_at
                        tweets.append({'status': status, 'date': tweet_date})
        except:
                tweets.append({'status': 'Follow us @HackedExistence', 'date': 'about 10 minutes ago'})
        return {'tweets': tweets}
		

templates/index.html

{% extends "base.html" %}
{% block content %}
        <div id="home_copy">
                {{ homepage.homecopy|safe }}
        </div>
        <a href="/beers/">View the Beers List!</a>
        <ul id="home_tweets">
                {% for tweet in tweets.tweets %}
                <li class="tweettext">{{ tweet.status }}</li>
                <li class="tweettime">{{ tweet.date }}</li>
                {% endfor %}
        </ul>
{% endblock %}