Social media

Feed

Get this site's feed in your feed reader.


The absurdly simple way to add content to Twitter via Django

Posted Monday, January 14th, 2008 at 11:51 a.m. by Matthew Waite

I haven’t found the right project to implement this yet, but I thought I would share it anyway.

Say you’ve got an application in Django. Say you’ve got a Twitteraccount for that application. Now you’d like your content to go fromyour Django app to your Twitter account.

There’s lots of ways to do this. Here’s an absurdly simple way: A save method and the Twitter API.

Let’s say you built a blog application in Django. You’d have a model that looked something like this:

class Posts(model.Model):
    headline = models.CharField(maxlength=255)
    ... other stuff ...

So, since you only have 140 characters in Twitter, you just wantyour headline and a link in your tweet. The easiest way I can think ofto do this is in a save method. Save methods in Django are where youwant something to happen between when the user clicks the save buttonand when it actually goes into the database. In this case, we want totake a couple of pieces of data, pass it to Twitter via its API, andthen save it to the database. To do this you have to define a savemethod. The whole thing -- all four lines of code -- looks like this:

def save(self):
    params = urllib.urlencode({'status': 'My latest: %s at www.yoururl.com'}) % self.headline
    o = urllib.urlopen("http://USERNAME:PASSWORD@twitter.com/statuses/update.xml?", params)
    super(statement, self).save()

So what’s happening here?

First line just defines the save method.

The second line creates a variable called params and then urlencodesthe string starting with ’status’. Since Twitter’s API is mostly a RESTinterface, you put all your data into the URL and Twitter interpretsthat. Thus, you have to make your content into a URL. Thus, urlencode.You can style this any way you want. The way I’ve done it, the tweetwould look like: My latest: This is a headline at hyperlinked url,probably tinyurl’d. You could make it whatever — change the words,directly link to the blog post using a get_absolute_url_method,whatever you want, keeping the 140 character limit. Go wild.

The third line creates a variable called “o” which sends a requestto the Twitter API url, with the username and password of the user inthe URL so it autheticates, and the parameters that you just URLencoded in the previous line. So, if you were implementing this, you’dchange USERNAME and PASSWORD with your username and password,obviously.

The fourth line then goes ahead and saves it all to the database.

That’s it. Four lines and your Django content is now feeding your Twitter account.

Comments are closed on this post

Current projects

Here's what I've launched lately

Recent speaking engagements

A list of where I've spoken lately.

Search

The complete archives, searchable, thanks to Google.