It was a bit tricky trying to find information on how to do this and StackOverflow seemed to be giving advice of all sorts except for code that actually worked.
StackOverflow in a nutshell. Sometimes it feels like people are just answering for the upvotes and not to actually answer the question...
Below is a working sample which uses Django's syndication framework the way it's meant to be used but also checks out nicely with any well known validator.
We create a class called MediaRssFeed which subclasses a built-in feed generator called Rss201rev2Feed.
MediaRssFeed allows us to declare the namespaces required for the thumbnail markup to be valid, but also allows us to insert additional elements into the item as it is rendered.
In our LatestNewsFeed class, we simply replace feed_type with MediaRssFeed and add a new function item_extra_kwargs() which returns information for the feed generator to use.
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Rss201rev2Feed
class MediaRssFeed(Rss201rev2Feed):
"""
Implement thumbnails which adhere to Yahoo Media RSS (mrss) feed.
@see http://djangosnippets.org/snippets/1648/
"""
def rss_attributes(self):
attrs = super(MediaRssFeed, self).rss_attributes()
attrs['xmlns:dc'] = "http://purl.org/dc/elements/1.1/"
attrs['xmlns:media'] = 'http://search.yahoo.com/mrss/'
return attrs
def add_item_elements(self, handler, item):
"""
Callback to add thumbnail element to each item (item/entry) element.
"""
super(MediaRssFeed, self).add_item_elements(handler, item)
thumbnail = { 'url': item['thumbnail_url'] }
if 'thumbnail_width' in item:
thumbnail['width'] = str(item['thumbnail_width'])
if 'thumbnail_height' in item:
thumbnail['height'] = str(item['thumbnail_height'])
handler.addQuickElement(u"media:thumbnail", '', thumbnail)
class LatestNewsFeed(Feed):
feed_type = MediaRssFeed
def item_extra_kwargs(self, article):
"""
Return a dictionary to the feedgenerator for each item to be added to the feed.
If the object is a Gallery, uses a random sample image for use as the feed Item
"""
image = article.get_main_image()
item = {
'thumbnail_url': generate_image_url(image, 300, 150, absolute = True),
# Optional
'thumbnail_width': 300,
'thumbnail_height': 150,
}
return item
# The rest of your feed class here as usual