Rendering a RSS feed in Django
Sunday, May 24th, 2009I have been working to get the new version of DEV360.com out the door and found myself in need of displaying RSS items from my Wordpress-powered blog on the DEV360 site which is developed in Django.
There were two libraries that I found for parsing RSS; RSS.py by Mark Nottingham which unfortunately didn’t support RSS 2.0, and Mark Pilgrim’s feedparser.py. I settled on the latter since it contains more features, has easier syntax and has better unit-test coverage.
For what I’m doing, a template tag works out best for rendering the RSS items; let’s fast-forward to the code:
foo.html:
{% load rss_feed %}
{% rss_feed %}
[application]/templatetags.py:
import feedparser
from datetime import datetime
from django.template import Library, Node
register = Library()
@register.simple_tag
def rss_feed(itemCount=5):
channel = feedparser.parse('http://blog.dev360.com/feed/')
html = []
html.append('<div id="rss-feed">')
html.append(' <h1>Latest blog posts</h1>')
html.append(' <ul>')
for entry in channel.entries[:itemCount]:
url = entry.id
title = entry.title
date = datetime.strptime(entry.date, "%a, %d %b %Y %H:%M:%S +0000");
html.append('<li><p><strong><a href="%s">%s</a></strong>' % (url, title));
html.append('%s</p></li>' % (date.strftime("%B %d, %Y")))
html.append(' </ul>')
html.append('</div>')
return "\n".join(html)