Adding Tag-based Feeds to Django Syndication

|

I just started generating feeds for my site using the Django Syndication Framework and it honestly only took about five minutes thanks to the docs. Unfortunately, it wasn’t that clear how to add feeds that filter the models it returns based on some common relationship (ie, tags!). I did figure it out after a little code-digging, and here is the result. If you use Jonathan Buchanan‘s django-tagging app, this should work as-is for you.

The following code goes in urls.py or perhaps feeds.py, depending on how anal you are (guess where mine is). As you can see, all you have to do is subclass Feed and add it to your feeds dict. There’s some tweaks one can do for a more enjoyable RSS experience, but those are coming when I finish my tumble log app. Hope this helps!

from xdissent.blog.models import Entry
from tagging.models import Tag, TaggedItem
from django.contrib.syndication.feeds import Feed
from models import Entry

class LatestEntries(Feed):
    title = 'xdissent.com Blog Feed'
    link = '/blog/'
    description = "Updates on changes and additions to xdissent.com"

    def items(self):
        return Entry.objects.filter(public=True)[:10]

class TaggedEntriesFeed(Feed):
    def get_object(self, bits):
        # don't worry about validation - will raise DoesNotExist if error
        tag = Tag.objects.get(name=bits[0])
        return tag

    def items(self, obj):
        return TaggedItem.objects.get_by_model(Entry.objects.filter(public=True), obj)[:10]

    def link(self, obj):
        # should probably be a call to Tag.get_absolute_url() or similar
        return '/tags/%s/' % obj

    def title(self, obj):
        return 'xdissent.com Feed for tag %s' % obj

    def description(self, obj):
        return 'Updates on changes and additions to xdissent.com tagged %s' % obj

feeds = {
    'latest': LatestEntries,
    'tags': TaggedEntriesFeed,
}

urlpatterns = patterns('',
    ...
    url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}, name='feeds'),
)

Comments

This might come in very handy. Thanks!

Post a comment: