Adding RSS feeds to Django Applications
Being a relatively ‘young’ framework, most of the requirements for building social applications works right out-of-the-box from Django. One such feature is ‘feeds’. Here is how I built ‘feeds’ for SOL.
URLs
I followed the convention and url for the feeds are in ‘/feeds/’. Make the below changes to urls.py.
urlpatterns += patterns('django.contrib.syndication.views',
(r'^feeds/(?P<url>.*)/$', 'feed', {'feed_dict': {
'latest': LatestSOLs,
'user': UserSOLs,
'group': GroupSOLs}
}
),
)
What this means is that, there are three feeds available - one of the latest entries, one for the user entries and another for the group. The corresponding functions should be in feeds.py.
Feeds
The easiest one is to create feed for all the entries: just derive from Feed class; define title, link and description for the feed; return the entries. Django does the rest of the stuff.
class LatestSOLs(Feed):
title = '%s : Latest SOLs' % settings.SITE_NAME
link = '/'
description = 'Latest entries to %s' % settings.SITE_NAME
def items(self):
return sol.objects.order_by('-date')[:settings.FEED_SIZE]
It gets little complex when parameters are passed via URL, user id or group id, and feed should be built accordingly. You need to find the object (user or group) and filter accordingly.
class UserSOLs(Feed):
title_template = 'feeds/title.html'
description_template = 'feeds/description.html'
def get_object(self, bits):
if len(bits) < 1:
raise ObjectDoesNotExist
return userprofile.objects.get(user__username__exact=bits[0])
def title(self, obj):
return "SOLs of '%s'" % obj.nickname
def link(self, obj):
return "/"
def description(self, obj):
return "SOLs recently posted by %s" % obj.nickname
def items(self, obj):
return sol.objects.filter(author__username=obj.user.username).order_by('-date')[:settings.FEED_SIZE]
Templates
You need to design a template for title and description of the feeds. They are pretty simple.
title.html
{{ obj.get_author_nickname }} - {{ obj.date|date:"M-d G:i" }}
It can be as simple as {{ obj.title }}
description.html
{{ obj.body }}
Feeds are ready. They need to be included in the home page templates so that browsers can identify them.
For all entries:
{% block feeds %}
<link rel="alternate" type="application/rss+xml" title="Public Feeds" href="/feeds/latest/
{%endblock feeds%}
For feeds specific to a user:
{% block feeds %}
<link rel="alternate" type="application/rss+xml" title="User Feeds" href="/feeds/user/{{u_id}}" />
{%endblock feeds%}
That’s all needed to enable feeds for your social application.
You can browse the code from google hosting.
References
http://blog.michaeltrier.com/2007/8/5/digging-into-django-syndication-framework
http://www.djangoproject.com/documentation/syndication_feeds/
http://www.andrlik.org/blog/2007/aug/03/fun-with-django-feeds/
del.icio.us Tags: django,rss,syndication
Technorati Tags: django,rss,syndication













