Serve your comments as a feed

It's quite useful to let your visitors track the comments of your weblog entries with RSS feeds. While displaying all recent comments is quite simple, there is no way in the defaults Feed class to to dynamically filter feeds-items by a given object.

So, how do I display all comments for a specific blog post in a feed? Here is the solution I use in this weblog. I've created a slightly modified Feed class:

from django.contrib.syndication.feeds import Feed
from django.contrib.comments.models import Comment

class CommentFeed(Feed):

    def __init__(self, entry_obj, request, slug='comments')
        self.title = 'Comments for "%s"' % entry_obj.title
        self.link = entry_obj.get_absolute_url()
        self._entry_obj = entry_obj
        super(CommentFeed, self).__init__(slug, request)

    def items(self):
        return Comment.objects.for_model(self._entry_obj) \
            .filter(is_public=True, is_removed=False) \
            .order_by('-submit_date')

    def item_pubdate(self, item):
        return item.submit_date

You pass the model instance to the class as it's first argument which is later used to filter all comments for the given instance. The slug argument, here comments, is used to call the specific templates for the feed. So don't forget to create the feed templates feeds/comments_title.html and feeds/comments_description.html. The rest is as usual as described in the documentation.

Unfortunately you can't use the brought with feed view django.contrib.syndication.views.feed to serve the feed data as it does not take any extra arguments. But a unique view for serving your comment feed is simple:

from django.http import HttpResponse
from weblog.models import Entry
from weblog.feed import CommentFeed

def details_feed(request, entry_slug):
    entry = Entry.objects.get(slug=entry_slug)
    feed = CommentFeed(entry, request).get_feed()
    response = HttpResponse(mimetype=feed.mime_type)
    feed.write(response, 'utf-8')
    return response

This view expects one argument, the slug for a model entry which instance i passed to the CommentFeed as described above. The rest of this function differs not much from the original feed view.


Comments closed

Sorry, new comments are no longer allowed for this entry.

Write me an email if you have feedback or any questions regarding this post. If you found this post useful and just want to say thank you then don't forget that I have an Amazon Wishlist. :-)


↑ to the elevators

© 2001—2010 Martin Mahner. This is an I ♥ Django Project.

Admin | Generated: Fri, 12 Mar 2010 22:07:22 +0100