The syndication feed framework

Django comes with a high-level syndication-feed-generating framework for creating RSS and Atom feeds.

To create any syndication feed, all you have to do is write a short Python class. You can create as many feeds as you want.

Django also comes with a lower-level feed-generating API. Use this if you want to generate feeds outside of a web context, or in some other lower-level way.

The high-level framework

Overview

The high-level feed-generating framework is supplied by the Feed class. To create a feed, write a Feed class and point to an instance of it in your URLconf.

Feed classes

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).

Feed classes subclass django.contrib.syndication.views.Feed. They can live anywhere in your codebase.

Instances of Feed classes are views which can be used in your URLconf.

A simple example

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

  1. from django.contrib.syndication.views import Feed
  2. from django.urls import reverse
  3. from policebeat.models import NewsItem
  4. class LatestEntriesFeed(Feed):
  5. title = "Police beat site news"
  6. link = "/sitenews/"
  7. description = "Updates on changes and additions to police beat central."
  8. def items(self):
  9. return NewsItem.objects.order_by('-pub_date')[:5]
  10. def item_title(self, item):
  11. return item.title
  12. def item_description(self, item):
  13. return item.description
  14. # item_link is only needed if NewsItem has no get_absolute_url method.
  15. def item_link(self, item):
  16. return reverse('news-item', args=[item.pk])

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

  1. from django.urls import path
  2. from myproject.feeds import LatestEntriesFeed
  3. urlpatterns = [
  4. # ...
  5. path('latest/feed/', LatestEntriesFeed()),
  6. # ...
  7. ]

Note:

  • The Feed class subclasses django.contrib.syndication.views.Feed.
  • title, link and description correspond to the standard RSS <title>, <link> and <description> elements, respectively.
  • items() is, 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.
  • If you’re creating an Atom feed, rather than an RSS feed, set the subtitle attribute instead of the description attribute. See Publishing Atom and RSS feeds in tandem, later, for an example.

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 string 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:

    See a complex example below that uses a description template.

    Feed.get_context_data(\*kwargs*)

    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:

    1. from mysite.models import Article
    2. from django.contrib.syndication.views import Feed
    3. class ArticlesFeed(Feed):
    4. title = "My articles"
    5. description_template = "feeds/articles.html"
    6. def items(self):
    7. return Article.objects.order_by('-pub_date')[:5]
    8. def get_context_data(self, **kwargs):
    9. context = super().get_context_data(**kwargs)
    10. context['foo'] = 'bar'
    11. return context

    And the template:

    1. Something about {{ foo }}: {{ obj.description }}

    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.

A complex example

The framework also supports more complex feeds, via arguments.

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.

The police beat feeds could be accessible via URLs like this:

  • /beats/613/rss/ – Returns recent crimes for beat 613.
  • /beats/1424/rss/ – Returns recent crimes for beat 1424.

These can be matched with a URLconf line such as:

  1. path('beats/<int:beat_id>/rss/', BeatFeed()),

Like a view, the arguments in the URL are passed to the get_object() method along with the request object.

Here’s the code for these beat-specific feeds:

  1. from django.contrib.syndication.views import Feed
  2. class BeatFeed(Feed):
  3. description_template = 'feeds/beat_description.html'
  4. def get_object(self, request, beat_id):
  5. return Beat.objects.get(pk=beat_id)
  6. def title(self, obj):
  7. return "Police beat central: Crimes for beat %s" % obj.beat
  8. def link(self, obj):
  9. return obj.get_absolute_url()
  10. def description(self, obj):
  11. return "Crimes recently reported in police beat %s" % obj.beat
  12. def items(self, obj):
  13. return Crime.objects.filter(beat=obj).order_by('-crime_date')[:30]

To generate the feed’s <title>, <link> and <description>, Django uses the title(), link() and description() methods. In the previous example, they were 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 as minimal as this:

  1. {{ 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.

Specifying the type of feed

By default, feeds produced in this framework use RSS 2.0.

To change that, add a feed_type attribute to your Feed class, like so:

  1. from django.utils.feedgenerator import Atom1Feed
  2. class MyFeed(Feed):
  3. feed_type = Atom1Feed

Note that you set feed_type to a class object, not an instance.

Currently available feed types are:

Enclosures

To specify enclosures, such as those used in creating podcast feeds, use the item_enclosures hook or, alternatively and if you only have a single enclosure per item, the item_enclosure_url, item_enclosure_length, and item_enclosure_mime_type hooks. See the ExampleFeed class below for usage examples.

Language

Feeds created by the syndication framework automatically include the appropriate <language> tag (RSS 2.0) or xml:lang attribute (Atom). By default, this is django.utils.translation.get_language(). You can change it by setting the language class attribute.

URLs

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. "https://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_ID setting.

Atom feeds require a <link rel="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.

Publishing Atom and RSS feeds in tandem

Some developers like to make available both Atom and RSS versions of their feeds. To do that, you can 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:

  1. from django.contrib.syndication.views import Feed
  2. from policebeat.models import NewsItem
  3. from django.utils.feedgenerator import Atom1Feed
  4. class RssSiteNewsFeed(Feed):
  5. title = "Police beat site news"
  6. link = "/sitenews/"
  7. description = "Updates on changes and additions to police beat central."
  8. def items(self):
  9. return NewsItem.objects.order_by('-pub_date')[:5]
  10. class AtomSiteNewsFeed(RssSiteNewsFeed):
  11. feed_type = Atom1Feed
  12. subtitle = 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 set the Atom feed’s subtitle to the RSS feed’s description, because it’s quite short already.

And the accompanying URLconf:

  1. from django.urls import path
  2. from myproject.feeds import AtomSiteNewsFeed, RssSiteNewsFeed
  3. urlpatterns = [
  4. # ...
  5. path('sitenews/rss/', RssSiteNewsFeed()),
  6. path('sitenews/atom/', AtomSiteNewsFeed()),
  7. # ...
  8. ]

Feed class reference

class views.Feed

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

  1. from django.contrib.syndication.views import Feed
  2. from django.utils import feedgenerator
  3. class ExampleFeed(Feed):
  4. # FEED TYPE -- Optional. This should be a class that subclasses
  5. # django.utils.feedgenerator.SyndicationFeed. This designates
  6. # which type of feed this should be: RSS 2.0, Atom 1.0, etc. If
  7. # you don't specify feed_type, your feed will be RSS 2.0. This
  8. # should be a class, not an instance of the class.
  9. feed_type = feedgenerator.Rss201rev2Feed
  10. # TEMPLATE NAMES -- Optional. These should be strings
  11. # representing names of Django templates that the system should
  12. # use in rendering the title and description of your feed items.
  13. # Both are optional. If a template is not specified, the
  14. # item_title() or item_description() methods are used instead.
  15. title_template = None
  16. description_template = None
  17. # LANGUAGE -- Optional. This should be a string specifying a language
  18. # code. Defaults to django.utils.translation.get_language().
  19. language = 'de'
  20. # TITLE -- One of the following three is required. The framework
  21. # looks for them in this order.
  22. def title(self, obj):
  23. """
  24. Takes the object returned by get_object() and returns the
  25. feed's title as a normal Python string.
  26. """
  27. def title(self):
  28. """
  29. Returns the feed's title as a normal Python string.
  30. """
  31. title = 'foo' # Hard-coded title.
  32. # LINK -- One of the following three is required. The framework
  33. # looks for them in this order.
  34. def link(self, obj):
  35. """
  36. # Takes the object returned by get_object() and returns the URL
  37. # of the HTML version of the feed as a normal Python string.
  38. """
  39. def link(self):
  40. """
  41. Returns the URL of the HTML version of the feed as a normal Python
  42. string.
  43. """
  44. link = '/blog/' # Hard-coded URL.
  45. # FEED_URL -- One of the following three is optional. The framework
  46. # looks for them in this order.
  47. def feed_url(self, obj):
  48. """
  49. # Takes the object returned by get_object() and returns the feed's
  50. # own URL as a normal Python string.
  51. """
  52. def feed_url(self):
  53. """
  54. Returns the feed's own URL as a normal Python string.
  55. """
  56. feed_url = '/blog/rss/' # Hard-coded URL.
  57. # GUID -- One of the following three is optional. The framework looks
  58. # for them in this order. This property is only used for Atom feeds
  59. # (where it is the feed-level ID element). If not provided, the feed
  60. # link is used as the ID.
  61. def feed_guid(self, obj):
  62. """
  63. Takes the object returned by get_object() and returns the globally
  64. unique ID for the feed as a normal Python string.
  65. """
  66. def feed_guid(self):
  67. """
  68. Returns the feed's globally unique ID as a normal Python string.
  69. """
  70. feed_guid = '/foo/bar/1234' # Hard-coded guid.
  71. # DESCRIPTION -- One of the following three is required. The framework
  72. # looks for them in this order.
  73. def description(self, obj):
  74. """
  75. Takes the object returned by get_object() and returns the feed's
  76. description as a normal Python string.
  77. """
  78. def description(self):
  79. """
  80. Returns the feed's description as a normal Python string.
  81. """
  82. description = 'Foo bar baz.' # Hard-coded description.
  83. # AUTHOR NAME --One of the following three is optional. The framework
  84. # looks for them in this order.
  85. def author_name(self, obj):
  86. """
  87. Takes the object returned by get_object() and returns the feed's
  88. author's name as a normal Python string.
  89. """
  90. def author_name(self):
  91. """
  92. Returns the feed's author's name as a normal Python string.
  93. """
  94. author_name = 'Sally Smith' # Hard-coded author name.
  95. # AUTHOR EMAIL --One of the following three is optional. The framework
  96. # looks for them in this order.
  97. def author_email(self, obj):
  98. """
  99. Takes the object returned by get_object() and returns the feed's
  100. author's email as a normal Python string.
  101. """
  102. def author_email(self):
  103. """
  104. Returns the feed's author's email as a normal Python string.
  105. """
  106. author_email = 'test@example.com' # Hard-coded author email.
  107. # AUTHOR LINK --One of the following three is optional. The framework
  108. # looks for them in this order. In each case, the URL should include
  109. # the "http://" and domain name.
  110. def author_link(self, obj):
  111. """
  112. Takes the object returned by get_object() and returns the feed's
  113. author's URL as a normal Python string.
  114. """
  115. def author_link(self):
  116. """
  117. Returns the feed's author's URL as a normal Python string.
  118. """
  119. author_link = 'https://www.example.com/' # Hard-coded author URL.
  120. # CATEGORIES -- One of the following three is optional. The framework
  121. # looks for them in this order. In each case, the method/attribute
  122. # should return an iterable object that returns strings.
  123. def categories(self, obj):
  124. """
  125. Takes the object returned by get_object() and returns the feed's
  126. categories as iterable over strings.
  127. """
  128. def categories(self):
  129. """
  130. Returns the feed's categories as iterable over strings.
  131. """
  132. categories = ("python", "django") # Hard-coded list of categories.
  133. # COPYRIGHT NOTICE -- One of the following three is optional. The
  134. # framework looks for them in this order.
  135. def feed_copyright(self, obj):
  136. """
  137. Takes the object returned by get_object() and returns the feed's
  138. copyright notice as a normal Python string.
  139. """
  140. def feed_copyright(self):
  141. """
  142. Returns the feed's copyright notice as a normal Python string.
  143. """
  144. feed_copyright = 'Copyright (c) 2007, Sally Smith' # Hard-coded copyright notice.
  145. # TTL -- One of the following three is optional. The framework looks
  146. # for them in this order. Ignored for Atom feeds.
  147. def ttl(self, obj):
  148. """
  149. Takes the object returned by get_object() and returns the feed's
  150. TTL (Time To Live) as a normal Python string.
  151. """
  152. def ttl(self):
  153. """
  154. Returns the feed's TTL as a normal Python string.
  155. """
  156. ttl = 600 # Hard-coded Time To Live.
  157. # ITEMS -- One of the following three is required. The framework looks
  158. # for them in this order.
  159. def items(self, obj):
  160. """
  161. Takes the object returned by get_object() and returns a list of
  162. items to publish in this feed.
  163. """
  164. def items(self):
  165. """
  166. Returns a list of items to publish in this feed.
  167. """
  168. items = ('Item 1', 'Item 2') # Hard-coded items.
  169. # GET_OBJECT -- This is required for feeds that publish different data
  170. # for different URL parameters. (See "A complex example" above.)
  171. def get_object(self, request, *args, **kwargs):
  172. """
  173. Takes the current request and the arguments from the URL, and
  174. returns an object represented by this feed. Raises
  175. django.core.exceptions.ObjectDoesNotExist on error.
  176. """
  177. # ITEM TITLE AND DESCRIPTION -- If title_template or
  178. # description_template are not defined, these are used instead. Both are
  179. # optional, by default they will use the string representation of the
  180. # item.
  181. def item_title(self, item):
  182. """
  183. Takes an item, as returned by items(), and returns the item's
  184. title as a normal Python string.
  185. """
  186. def item_title(self):
  187. """
  188. Returns the title for every item in the feed.
  189. """
  190. item_title = 'Breaking News: Nothing Happening' # Hard-coded title.
  191. def item_description(self, item):
  192. """
  193. Takes an item, as returned by items(), and returns the item's
  194. description as a normal Python string.
  195. """
  196. def item_description(self):
  197. """
  198. Returns the description for every item in the feed.
  199. """
  200. item_description = 'A description of the item.' # Hard-coded description.
  201. def get_context_data(self, **kwargs):
  202. """
  203. Returns a dictionary to use as extra context if either
  204. description_template or item_template are used.
  205. Default implementation preserves the old behavior
  206. of using {'obj': item, 'site': current_site} as the context.
  207. """
  208. # ITEM LINK -- One of these three is required. The framework looks for
  209. # them in this order.
  210. # First, the framework tries the two methods below, in
  211. # order. Failing that, it falls back to the get_absolute_url()
  212. # method on each item returned by items().
  213. def item_link(self, item):
  214. """
  215. Takes an item, as returned by items(), and returns the item's URL.
  216. """
  217. def item_link(self):
  218. """
  219. Returns the URL for every item in the feed.
  220. """
  221. # ITEM_GUID -- The following method is optional. If not provided, the
  222. # item's link is used by default.
  223. def item_guid(self, obj):
  224. """
  225. Takes an item, as return by items(), and returns the item's ID.
  226. """
  227. # ITEM_GUID_IS_PERMALINK -- The following method is optional. If
  228. # provided, it sets the 'isPermaLink' attribute of an item's
  229. # GUID element. This method is used only when 'item_guid' is
  230. # specified.
  231. def item_guid_is_permalink(self, obj):
  232. """
  233. Takes an item, as returned by items(), and returns a boolean.
  234. """
  235. item_guid_is_permalink = False # Hard coded value
  236. # ITEM AUTHOR NAME -- One of the following three is optional. The
  237. # framework looks for them in this order.
  238. def item_author_name(self, item):
  239. """
  240. Takes an item, as returned by items(), and returns the item's
  241. author's name as a normal Python string.
  242. """
  243. def item_author_name(self):
  244. """
  245. Returns the author name for every item in the feed.
  246. """
  247. item_author_name = 'Sally Smith' # Hard-coded author name.
  248. # ITEM AUTHOR EMAIL --One of the following three is optional. The
  249. # framework looks for them in this order.
  250. #
  251. # If you specify this, you must specify item_author_name.
  252. def item_author_email(self, obj):
  253. """
  254. Takes an item, as returned by items(), and returns the item's
  255. author's email as a normal Python string.
  256. """
  257. def item_author_email(self):
  258. """
  259. Returns the author email for every item in the feed.
  260. """
  261. item_author_email = 'test@example.com' # Hard-coded author email.
  262. # ITEM AUTHOR LINK -- One of the following three is optional. The
  263. # framework looks for them in this order. In each case, the URL should
  264. # include the "http://" and domain name.
  265. #
  266. # If you specify this, you must specify item_author_name.
  267. def item_author_link(self, obj):
  268. """
  269. Takes an item, as returned by items(), and returns the item's
  270. author's URL as a normal Python string.
  271. """
  272. def item_author_link(self):
  273. """
  274. Returns the author URL for every item in the feed.
  275. """
  276. item_author_link = 'https://www.example.com/' # Hard-coded author URL.
  277. # ITEM ENCLOSURES -- One of the following three is optional. The
  278. # framework looks for them in this order. If one of them is defined,
  279. # ``item_enclosure_url``, ``item_enclosure_length``, and
  280. # ``item_enclosure_mime_type`` will have no effect.
  281. def item_enclosures(self, item):
  282. """
  283. Takes an item, as returned by items(), and returns a list of
  284. ``django.utils.feedgenerator.Enclosure`` objects.
  285. """
  286. def item_enclosures(self):
  287. """
  288. Returns the ``django.utils.feedgenerator.Enclosure`` list for every
  289. item in the feed.
  290. """
  291. item_enclosures = [] # Hard-coded enclosure list
  292. # ITEM ENCLOSURE URL -- One of these three is required if you're
  293. # publishing enclosures and you're not using ``item_enclosures``. The
  294. # framework looks for them in this order.
  295. def item_enclosure_url(self, item):
  296. """
  297. Takes an item, as returned by items(), and returns the item's
  298. enclosure URL.
  299. """
  300. def item_enclosure_url(self):
  301. """
  302. Returns the enclosure URL for every item in the feed.
  303. """
  304. item_enclosure_url = "/foo/bar.mp3" # Hard-coded enclosure link.
  305. # ITEM ENCLOSURE LENGTH -- One of these three is required if you're
  306. # publishing enclosures and you're not using ``item_enclosures``. The
  307. # framework looks for them in this order. In each case, the returned
  308. # value should be either an integer, or a string representation of the
  309. # integer, in bytes.
  310. def item_enclosure_length(self, item):
  311. """
  312. Takes an item, as returned by items(), and returns the item's
  313. enclosure length.
  314. """
  315. def item_enclosure_length(self):
  316. """
  317. Returns the enclosure length for every item in the feed.
  318. """
  319. item_enclosure_length = 32000 # Hard-coded enclosure length.
  320. # ITEM ENCLOSURE MIME TYPE -- One of these three is required if you're
  321. # publishing enclosures and you're not using ``item_enclosures``. The
  322. # framework looks for them in this order.
  323. def item_enclosure_mime_type(self, item):
  324. """
  325. Takes an item, as returned by items(), and returns the item's
  326. enclosure MIME type.
  327. """
  328. def item_enclosure_mime_type(self):
  329. """
  330. Returns the enclosure MIME type for every item in the feed.
  331. """
  332. item_enclosure_mime_type = "audio/mpeg" # Hard-coded enclosure MIME type.
  333. # ITEM PUBDATE -- It's optional to use one of these three. This is a
  334. # hook that specifies how to get the pubdate for a given item.
  335. # In each case, the method/attribute should return a Python
  336. # datetime.datetime object.
  337. def item_pubdate(self, item):
  338. """
  339. Takes an item, as returned by items(), and returns the item's
  340. pubdate.
  341. """
  342. def item_pubdate(self):
  343. """
  344. Returns the pubdate for every item in the feed.
  345. """
  346. item_pubdate = datetime.datetime(2005, 5, 3) # Hard-coded pubdate.
  347. # ITEM UPDATED -- It's optional to use one of these three. This is a
  348. # hook that specifies how to get the updateddate for a given item.
  349. # In each case, the method/attribute should return a Python
  350. # datetime.datetime object.
  351. def item_updateddate(self, item):
  352. """
  353. Takes an item, as returned by items(), and returns the item's
  354. updateddate.
  355. """
  356. def item_updateddate(self):
  357. """
  358. Returns the updateddate for every item in the feed.
  359. """
  360. item_updateddate = datetime.datetime(2005, 5, 3) # Hard-coded updateddate.
  361. # ITEM CATEGORIES -- It's optional to use one of these three. This is
  362. # a hook that specifies how to get the list of categories for a given
  363. # item. In each case, the method/attribute should return an iterable
  364. # object that returns strings.
  365. def item_categories(self, item):
  366. """
  367. Takes an item, as returned by items(), and returns the item's
  368. categories.
  369. """
  370. def item_categories(self):
  371. """
  372. Returns the categories for every item in the feed.
  373. """
  374. item_categories = ("python", "django") # Hard-coded categories.
  375. # ITEM COPYRIGHT NOTICE (only applicable to Atom feeds) -- One of the
  376. # following three is optional. The framework looks for them in this
  377. # order.
  378. def item_copyright(self, obj):
  379. """
  380. Takes an item, as returned by items(), and returns the item's
  381. copyright notice as a normal Python string.
  382. """
  383. def item_copyright(self):
  384. """
  385. Returns the copyright notice for every item in the feed.
  386. """
  387. item_copyright = 'Copyright (c) 2007, Sally Smith' # Hard-coded copyright notice.
  388. # ITEM COMMENTS URL -- It's optional to use one of these three. This is
  389. # a hook that specifies how to get the URL of a page for comments for a
  390. # given item.
  391. def item_comments(self, obj):
  392. """
  393. Takes an item, as returned by items(), and returns the item's
  394. comments URL as a normal Python string.
  395. """
  396. def item_comments(self):
  397. """
  398. Returns the comments URL for every item in the feed.
  399. """
  400. item_comments = 'https://www.example.com/comments' # Hard-coded comments URL

Changed in Django 3.2:

Support for a comments URL per feed item was added through the item_comments hook.

The low-level framework

Behind the scenes, the high-level RSS framework uses a lower-level framework for generating feeds’ XML. This framework lives in a single module: django/utils/feedgenerator.py.

You use this framework on your own, for lower-level feed generation. You can also create custom feed generator subclasses for use with the feed_type Feed option.

SyndicationFeed classes

The feedgenerator module contains a base class:

and several subclasses:

Each of these three classes knows how to render a certain type of feed as XML. They share this interface:

SyndicationFeed.__init__()

Initialize the feed with the given dictionary of metadata, which applies to the entire feed. Required keyword arguments are:

  • title
  • link
  • description

There’s also a bunch of other optional keywords:

  • language
  • author_email
  • author_name
  • author_link
  • subtitle
  • categories
  • feed_url
  • feed_copyright
  • feed_guid
  • ttl

Any extra keyword arguments you pass to __init__ will be stored in self.feed for use with custom feed generators.

All parameters should be strings, except categories, which should be a sequence of strings. Beware that some control characters are not allowed in XML documents. If your content has some of them, you might encounter a ValueError when producing the feed.

SyndicationFeed.add_item()

Add an item to the feed with the given parameters.

Required keyword arguments are:

  • title
  • link
  • description

Optional keyword arguments are:

  • author_email
  • author_name
  • author_link
  • pubdate
  • comments
  • unique_id
  • enclosures
  • categories
  • item_copyright
  • ttl
  • updateddate

Extra keyword arguments will be stored for custom feed generators.

All parameters, if given, should be strings, except:

SyndicationFeed.write()

Outputs the feed in the given encoding to outfile, which is a file-like object.

SyndicationFeed.writeString()

Returns the feed as a string in the given encoding.

For example, to create an Atom 1.0 feed and print it to standard output:

  1. >>> from django.utils import feedgenerator
  2. >>> from datetime import datetime
  3. >>> f = feedgenerator.Atom1Feed(
  4. ... title="My Blog",
  5. ... link="https://www.example.com/",
  6. ... description="In which I write about what I ate today.",
  7. ... language="en",
  8. ... author_name="Myself",
  9. ... feed_url="https://example.com/atom.xml")
  10. >>> f.add_item(title="Hot dog today",
  11. ... link="https://www.example.com/entries/1/",
  12. ... pubdate=datetime.now(),
  13. ... description="<p>Today I had a Vienna Beef hot dog. It was pink, plump and perfect.</p>")
  14. >>> print(f.writeString('UTF-8'))
  15. <?xml version="1.0" encoding="UTF-8"?>
  16. <feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
  17. ...
  18. </feed>

Custom feed generators

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:

  1. class iTunesFeed(Rss201rev2Feed):
  2. def root_attributes(self):
  3. attrs = super().root_attributes()
  4. attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
  5. return attrs
  6. def add_root_elements(self, handler):
  7. super().add_root_elements(handler)
  8. handler.addQuickElement('itunes:explicit', 'clean')

There’s a lot more work to be done for a complete custom feed class, but the above example should demonstrate the basic idea.