A Feed class is a Python
class that represents a syndication feed. A feed can be simple (e.g.,
a “site news” feed, or a basic feed displaying the latest entries of a
blog) or more complex (e.g., a feed displaying all the blog entries in
a particular category, where the category is variable).

This simple example, taken from a hypothetical police beat news site describes
a feed of the latest five news items:

fromdjango.contrib.syndication.viewsimportFeedfromdjango.core.urlresolversimportreversefrompolicebeat.modelsimportNewsItemclassLatestEntriesFeed(Feed):title="Police beat site news"link="/sitenews/"description="Updates on changes and additions to police beat central."defitems(self):returnNewsItem.objects.order_by('-pub_date')[:5]defitem_title(self,item):returnitem.titledefitem_description(self,item):returnitem.description# item_link is only needed if NewsItem has no get_absolute_url method.defitem_link(self,item):returnreverse('news-item',args=[item.pk])

To connect a URL to this feed, put an instance of the Feed object in
your URLconf. For example:

items() is, simply, a method that returns a list of objects that
should be included in the feed as <item> elements. Although this
example returns NewsItem objects using Django’s
object-relational mapper, items()
doesn’t have to return model instances. Although you get a few bits of
functionality “for free” by using Django models, items() can
return any type of object you want.

One thing is left to do. In an RSS feed, each <item> has a <title>,
<link> and <description>. We need to tell the framework what data to put
into those elements.

For the contents of <title> and <description>, Django tries
calling the methods item_title() and item_description() on
the Feed class. They are passed
a single parameter, item, which is the object itself. These are
optional; by default, the unicode representation of the object is used for
both.

If you want to do any special formatting for either the title or
description, Django templates can be used
instead. Their paths can be specified with the title_template and
description_template attributes on the
Feed class. The templates are
rendered for each item and are passed two template context variables:

{{obj}} – The current object (one of whichever objects you
returned in items()).

There is also a way to pass additional information to title and description
templates, if you need to supply more than the two variables mentioned
before. You can provide your implementation of get_context_data method
in your Feed subclass. For example:

This method will be called once per each item in the list returned by
items() with the following keyword arguments:

item: the current item. For backward compatibility reasons, the name
of this context variable is {{obj}}.

obj: the object returned by get_object(). By default this is not
exposed to the templates to avoid confusion with {{obj}} (see above),
but you can use it in your implementation of get_context_data().

site: current site as described above.

request: current request.

The behavior of get_context_data() mimics that of
generic views - you’re supposed to call
super() to retrieve context data from parent class, add your data
and return the modified dictionary.

To specify the contents of <link>, you have two options. For each item
in items(), Django first tries calling the
item_link() method on the
Feed class. In a similar way to
the title and description, it is passed it a single parameter,
item. If that method doesn’t exist, Django tries executing a
get_absolute_url() method on that object. Both
get_absolute_url() and item_link() should return the
item’s URL as a normal Python string. As with get_absolute_url(), the
result of item_link() will be included directly in the URL, so you
are responsible for doing all necessary URL quoting and conversion to
ASCII inside the method itself.

For example, a website could offer an RSS feed of recent crimes for every
police beat in a city. It’d be silly to create a separate
Feed class for each police beat; that
would violate the DRY principle and would couple data to
programming logic. Instead, the syndication framework lets you access the
arguments passed from your URLconf so feeds can output
items based on information in the feed’s URL.

To generate the feed’s <title>, <link> and <description>, Django
uses the title(), link() and description() methods. In
the previous example, they were simple string class attributes, but this example
illustrates that they can be either strings or methods. For each of
title, link and description, Django follows this
algorithm:

First, it tries to call a method, passing the obj argument, where
obj is the object returned by get_object().

Failing that, it tries to call a method with no arguments.

Failing that, it uses the class attribute.

Also note that items() also follows the same algorithm – first, it
tries items(obj), then items(), then finally an items
class attribute (which should be a list).

We are using a template for the item descriptions. It can be very simple:

{{obj.description}}

However, you are free to add formatting as desired.

The ExampleFeed class below gives full documentation on methods and
attributes of Feed classes.

To specify enclosures, such as those used in creating podcast feeds, use the
item_enclosure_url, item_enclosure_length and
item_enclosure_mime_type hooks. See the ExampleFeed class below for
usage examples.

The link method/attribute can return either an absolute path (e.g.
"/blog/") or a URL with the fully-qualified domain and protocol (e.g.
"http://www.example.com/blog/"). If link doesn’t return the domain,
the syndication framework will insert the domain of the current site, according
to your SITE_IDsetting.

Atom feeds require a <linkrel="self"> that defines the feed’s current
location. The syndication framework populates this automatically, using the
domain of the current site according to the SITE_ID setting.

Some developers like to make available both Atom and RSS versions of their
feeds. That’s easy to do with Django: Just create a subclass of your
Feed
class and set the feed_type to something different. Then update your
URLconf to add the extra versions.

Here’s a full example:

fromdjango.contrib.syndication.viewsimportFeedfrompolicebeat.modelsimportNewsItemfromdjango.utils.feedgeneratorimportAtom1FeedclassRssSiteNewsFeed(Feed):title="Police beat site news"link="/sitenews/"description="Updates on changes and additions to police beat central."defitems(self):returnNewsItem.objects.order_by('-pub_date')[:5]classAtomSiteNewsFeed(RssSiteNewsFeed):feed_type=Atom1Feedsubtitle=RssSiteNewsFeed.description

Note

In this example, the RSS feed uses a description while the Atom
feed uses a subtitle. That’s because Atom feeds don’t provide for
a feed-level “description,” but they do provide for a “subtitle.”

If you provide a description in your
Feed class, Django will not
automatically put that into the subtitle element, because a
subtitle and description are not necessarily the same thing. Instead, you
should define a subtitle attribute.

In the above example, we simply set the Atom feed’s subtitle to the
RSS feed’s description, because it’s quite short already.

This example illustrates all possible attributes and methods for a
Feed class:

fromdjango.contrib.syndication.viewsimportFeedfromdjango.utilsimportfeedgeneratorclassExampleFeed(Feed):# FEED TYPE -- Optional. This should be a class that subclasses# django.utils.feedgenerator.SyndicationFeed. This designates# which type of feed this should be: RSS 2.0, Atom 1.0, etc. If# you don't specify feed_type, your feed will be RSS 2.0. This# should be a class, not an instance of the class.feed_type=feedgenerator.Rss201rev2Feed# TEMPLATE NAMES -- Optional. These should be strings# representing names of Django templates that the system should# use in rendering the title and description of your feed items.# Both are optional. If a template is not specified, the# item_title() or item_description() methods are used instead.title_template=Nonedescription_template=None# TITLE -- One of the following three is required. The framework# looks for them in this order.deftitle(self,obj):""" Takes the object returned by get_object() and returns the feed's title as a normal Python string. """deftitle(self):""" Returns the feed's title as a normal Python string. """title='foo'# Hard-coded title.# LINK -- One of the following three is required. The framework# looks for them in this order.deflink(self,obj):""" # Takes the object returned by get_object() and returns the URL # of the HTML version of the feed as a normal Python string. """deflink(self):""" Returns the URL of the HTML version of the feed as a normal Python string. """link='/blog/'# Hard-coded URL.# FEED_URL -- One of the following three is optional. The framework# looks for them in this order.deffeed_url(self,obj):""" # Takes the object returned by get_object() and returns the feed's # own URL as a normal Python string. """deffeed_url(self):""" Returns the feed's own URL as a normal Python string. """feed_url='/blog/rss/'# Hard-coded URL.# GUID -- One of the following three is optional. The framework looks# for them in this order. This property is only used for Atom feeds# (where it is the feed-level ID element). If not provided, the feed# link is used as the ID.deffeed_guid(self,obj):""" Takes the object returned by get_object() and returns the globally unique ID for the feed as a normal Python string. """deffeed_guid(self):""" Returns the feed's globally unique ID as a normal Python string. """feed_guid='/foo/bar/1234'# Hard-coded guid.# DESCRIPTION -- One of the following three is required. The framework# looks for them in this order.defdescription(self,obj):""" Takes the object returned by get_object() and returns the feed's description as a normal Python string. """defdescription(self):""" Returns the feed's description as a normal Python string. """description='Foo bar baz.'# Hard-coded description.# AUTHOR NAME --One of the following three is optional. The framework# looks for them in this order.defauthor_name(self,obj):""" Takes the object returned by get_object() and returns the feed's author's name as a normal Python string. """defauthor_name(self):""" Returns the feed's author's name as a normal Python string. """author_name='Sally Smith'# Hard-coded author name.# AUTHOR EMAIL --One of the following three is optional. The framework# looks for them in this order.defauthor_email(self,obj):""" Takes the object returned by get_object() and returns the feed's author's email as a normal Python string. """defauthor_email(self):""" Returns the feed's author's email as a normal Python string. """author_email='test@example.com'# Hard-coded author email.# AUTHOR LINK --One of the following three is optional. The framework# looks for them in this order. In each case, the URL should include# the "http://" and domain name.defauthor_link(self,obj):""" Takes the object returned by get_object() and returns the feed's author's URL as a normal Python string. """defauthor_link(self):""" Returns the feed's author's URL as a normal Python string. """author_link='http://www.example.com/'# Hard-coded author URL.# CATEGORIES -- One of the following three is optional. The framework# looks for them in this order. In each case, the method/attribute# should return an iterable object that returns strings.defcategories(self,obj):""" Takes the object returned by get_object() and returns the feed's categories as iterable over strings. """defcategories(self):""" Returns the feed's categories as iterable over strings. """categories=("python","django")# Hard-coded list of categories.# COPYRIGHT NOTICE -- One of the following three is optional. The# framework looks for them in this order.deffeed_copyright(self,obj):""" Takes the object returned by get_object() and returns the feed's copyright notice as a normal Python string. """deffeed_copyright(self):""" Returns the feed's copyright notice as a normal Python string. """feed_copyright='Copyright (c) 2007, Sally Smith'# Hard-coded copyright notice.# TTL -- One of the following three is optional. The framework looks# for them in this order. Ignored for Atom feeds.defttl(self,obj):""" Takes the object returned by get_object() and returns the feed's TTL (Time To Live) as a normal Python string. """defttl(self):""" Returns the feed's TTL as a normal Python string. """ttl=600# Hard-coded Time To Live.# ITEMS -- One of the following three is required. The framework looks# for them in this order.defitems(self,obj):""" Takes the object returned by get_object() and returns a list of items to publish in this feed. """defitems(self):""" Returns a list of items to publish in this feed. """items=('Item 1','Item 2')# Hard-coded items.# GET_OBJECT -- This is required for feeds that publish different data# for different URL parameters. (See "A complex example" above.)defget_object(self,request,*args,**kwargs):""" Takes the current request and the arguments from the URL, and returns an object represented by this feed. Raises django.core.exceptions.ObjectDoesNotExist on error. """# ITEM TITLE AND DESCRIPTION -- If title_template or# description_template are not defined, these are used instead. Both are# optional, by default they will use the unicode representation of the# item.defitem_title(self,item):""" Takes an item, as returned by items(), and returns the item's title as a normal Python string. """defitem_title(self):""" Returns the title for every item in the feed. """item_title='Breaking News: Nothing Happening'# Hard-coded title.defitem_description(self,item):""" Takes an item, as returned by items(), and returns the item's description as a normal Python string. """defitem_description(self):""" Returns the description for every item in the feed. """item_description='A description of the item.'# Hard-coded description.defget_context_data(self,**kwargs):""" Returns a dictionary to use as extra context if either description_template or item_template are used. Default implementation preserves the old behavior of using {'obj': item, 'site': current_site} as the context. """# ITEM LINK -- One of these three is required. The framework looks for# them in this order.# First, the framework tries the two methods below, in# order. Failing that, it falls back to the get_absolute_url()# method on each item returned by items().defitem_link(self,item):""" Takes an item, as returned by items(), and returns the item's URL. """defitem_link(self):""" Returns the URL for every item in the feed. """# ITEM_GUID -- The following method is optional. If not provided, the# item's link is used by default.defitem_guid(self,obj):""" Takes an item, as return by items(), and returns the item's ID. """# ITEM_GUID_IS_PERMALINK -- The following method is optional. If# provided, it sets the 'isPermaLink' attribute of an item's# GUID element. This method is used only when 'item_guid' is# specified.defitem_guid_is_permalink(self,obj):""" Takes an item, as returned by items(), and returns a boolean. """item_guid_is_permalink=False# Hard coded value# ITEM AUTHOR NAME -- One of the following three is optional. The# framework looks for them in this order.defitem_author_name(self,item):""" Takes an item, as returned by items(), and returns the item's author's name as a normal Python string. """defitem_author_name(self):""" Returns the author name for every item in the feed. """item_author_name='Sally Smith'# Hard-coded author name.# ITEM AUTHOR EMAIL --One of the following three is optional. The# framework looks for them in this order.## If you specify this, you must specify item_author_name.defitem_author_email(self,obj):""" Takes an item, as returned by items(), and returns the item's author's email as a normal Python string. """defitem_author_email(self):""" Returns the author email for every item in the feed. """item_author_email='test@example.com'# Hard-coded author email.# ITEM AUTHOR LINK -- One of the following three is optional. The# framework looks for them in this order. In each case, the URL should# include the "http://" and domain name.## If you specify this, you must specify item_author_name.defitem_author_link(self,obj):""" Takes an item, as returned by items(), and returns the item's author's URL as a normal Python string. """defitem_author_link(self):""" Returns the author URL for every item in the feed. """item_author_link='http://www.example.com/'# Hard-coded author URL.# ITEM ENCLOSURE URL -- One of these three is required if you're# publishing enclosures. The framework looks for them in this order.defitem_enclosure_url(self,item):""" Takes an item, as returned by items(), and returns the item's enclosure URL. """defitem_enclosure_url(self):""" Returns the enclosure URL for every item in the feed. """item_enclosure_url="/foo/bar.mp3"# Hard-coded enclosure link.# ITEM ENCLOSURE LENGTH -- One of these three is required if you're# publishing enclosures. The framework looks for them in this order.# In each case, the returned value should be either an integer, or a# string representation of the integer, in bytes.defitem_enclosure_length(self,item):""" Takes an item, as returned by items(), and returns the item's enclosure length. """defitem_enclosure_length(self):""" Returns the enclosure length for every item in the feed. """item_enclosure_length=32000# Hard-coded enclosure length.# ITEM ENCLOSURE MIME TYPE -- One of these three is required if you're# publishing enclosures. The framework looks for them in this order.defitem_enclosure_mime_type(self,item):""" Takes an item, as returned by items(), and returns the item's enclosure MIME type. """defitem_enclosure_mime_type(self):""" Returns the enclosure MIME type for every item in the feed. """item_enclosure_mime_type="audio/mpeg"# Hard-coded enclosure MIME type.# ITEM PUBDATE -- It's optional to use one of these three. This is a# hook that specifies how to get the pubdate for a given item.# In each case, the method/attribute should return a Python# datetime.datetime object.defitem_pubdate(self,item):""" Takes an item, as returned by items(), and returns the item's pubdate. """defitem_pubdate(self):""" Returns the pubdate for every item in the feed. """item_pubdate=datetime.datetime(2005,5,3)# Hard-coded pubdate.# ITEM UPDATED -- It's optional to use one of these three. This is a# hook that specifies how to get the updateddate for a given item.# In each case, the method/attribute should return a Python# datetime.datetime object.defitem_updateddate(self,item):""" Takes an item, as returned by items(), and returns the item's updateddate. """defitem_updateddate(self):""" Returns the updateddated for every item in the feed. """item_updateddate=datetime.datetime(2005,5,3)# Hard-coded updateddate.# ITEM CATEGORIES -- It's optional to use one of these three. This is# a hook that specifies how to get the list of categories for a given# item. In each case, the method/attribute should return an iterable# object that returns strings.defitem_categories(self,item):""" Takes an item, as returned by items(), and returns the item's categories. """defitem_categories(self):""" Returns the categories for every item in the feed. """item_categories=("python","django")# Hard-coded categories.# ITEM COPYRIGHT NOTICE (only applicable to Atom feeds) -- One of the# following three is optional. The framework looks for them in this# order.defitem_copyright(self,obj):""" Takes an item, as returned by items(), and returns the item's copyright notice as a normal Python string. """defitem_copyright(self):""" Returns the copyright notice for every item in the feed. """item_copyright='Copyright (c) 2007, Sally Smith'# Hard-coded copyright notice.

If you need to produce a custom feed format, you’ve got a couple of options.

If the feed format is totally custom, you’ll want to subclass
SyndicationFeed and completely replace the write() and
writeString() methods.

However, if the feed format is a spin-off of RSS or Atom (i.e. GeoRSS, Apple’s
iTunes podcast format, etc.), you’ve got a better choice. These types of
feeds typically add extra elements and/or attributes to the underlying format,
and there are a set of methods that SyndicationFeed calls to get these extra
attributes. Thus, you can subclass the appropriate feed generator class
(Atom1Feed or Rss201rev2Feed) and extend these callbacks. They are:

SyndicationFeed.root_attributes(self,)

Return a dict of attributes to add to the root feed element
(feed/channel).

SyndicationFeed.add_root_elements(self,handler)

Callback to add elements inside the root feed element
(feed/channel). handler is an
XMLGenerator from Python’s built-in SAX library;
you’ll call methods on it to add to the XML document in process.

SyndicationFeed.item_attributes(self,item)

Return a dict of attributes to add to each item (item/entry)
element. The argument, item, is a dictionary of all the data passed to
SyndicationFeed.add_item().

SyndicationFeed.add_item_elements(self,handler,item)

Callback to add elements to each item (item/entry) element.
handler and item are as above.

Warning

If you override any of these methods, be sure to call the superclass methods
since they add the required elements for each feed format.

For example, you might start implementing an iTunes RSS feed generator like so: