The syndication feed framework

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

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

Django also comes with a lower-level feed-generating API. Use this ifyou want to generate feeds outside of a Web context, or in some otherlower-level way.

The high-level framework

Overview

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

Feed classes

A Feed class is a Pythonclass 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 ablog) or more complex (e.g., a feed displaying all the blog entries ina 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 classesare views which can be used in your URLconf.

A simple example

This simple example, taken from a hypothetical police beat news site describesa 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.  
  5. class LatestEntriesFeed(Feed):
  6. title = "Police beat site news"
  7. link = "/sitenews/"
  8. description = "Updates on changes and additions to police beat central."
  9.  
  10. def items(self):
  11. return NewsItem.objects.order_by('-pub_date')[:5]
  12.  
  13. def item_title(self, item):
  14. return item.title
  15.  
  16. def item_description(self, item):
  17. return item.description
  18.  
  19. # item_link is only needed if NewsItem has no get_absolute_url method.
  20. def item_link(self, item):
  21. return reverse('news-item', args=[item.pk])

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

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

Note:

  • The Feed class subclasses django.contrib.syndication.views.Feed.
  • title, link and description correspond to thestandard RSS <title>, <link> and <description> elements,respectively.
  • items() is, a method that returns a list of objects that should beincluded in the feed as <item> elements. Although this example returnsNewsItem 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 Djangomodels, items() can return any type of object you want.
  • If you’re creating an Atom feed, rather than an RSS feed, set thesubtitle 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 putinto those elements.

  • For the contents of <title> and <description>, Django triescalling the methods item_title() and item_description() onthe Feed class. They are passeda single parameter, item, which is the object itself. These areoptional; by default, the string representation of the object is used forboth.

If you want to do any special formatting for either the title ordescription, Django templates can be usedinstead. Their paths can be specified with the title_template anddescription_template attributes on theFeed class. The templates arerendered for each item and are passed two template context variables:

  • {{ obj }} – The current object (one of whichever objects youreturned in items()).
  • {{ site }} – A django.contrib.sites.models.Site objectrepresenting the current site. This is useful for {{ site.domain}} or {{ site.name }}. If you do not have the Django sitesframework installed, this will be set to aRequestSite object. See theRequestSite section of the sites framework documentation for more.See a complex example below that uses a description template.

  • Feed.getcontext_data(**kwargs_)

  • There is also a way to pass additional information to title and descriptiontemplates, if you need to supply more than the two variables mentionedbefore. You can provide your implementation of get_context_data methodin your Feed subclass. For example:
  1. from mysite.models import Article
  2. from django.contrib.syndication.views import Feed
  3.  
  4. class ArticlesFeed(Feed):
  5. title = "My articles"
  6. description_template = "feeds/articles.html"
  7.  
  8. def items(self):
  9. return Article.objects.order_by('-pub_date')[:5]
  10.  
  11. def get_context_data(self, **kwargs):
  12. context = super().get_context_data(**kwargs)
  13. context['foo'] = 'bar'
  14. return context

And the template:

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

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

  • item: the current item. For backward compatibility reasons, the nameof this context variable is {{ obj }}.
  • obj: the object returned by get_object(). By default this is notexposed 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 ofgeneric views - you’re supposed to callsuper() to retrieve context data from parent class, add your dataand return the modified dictionary.
  • To specify the contents of <link>, you have two options. For each itemin items(), Django first tries calling theitem_link() method on theFeed class. In a similar way tothe title and description, it is passed it a single parameter,item. If that method doesn’t exist, Django tries executing aget_absolute_url() method on that object. Bothget_absolute_url() and item_link() should return theitem’s URL as a normal Python string. As with get_absolute_url(), theresult of item_link() will be included directly in the URL, so youare responsible for doing all necessary URL quoting and conversion toASCII 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 everypolice beat in a city. It’d be silly to create a separateFeed class for each police beat; thatwould violate the DRY principle and would couple data toprogramming logic. Instead, the syndication framework lets you access thearguments passed from your URLconf so feeds can outputitems 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.  
  3. class BeatFeed(Feed):
  4. description_template = 'feeds/beat_description.html'
  5.  
  6. def get_object(self, request, beat_id):
  7. return Beat.objects.get(pk=beat_id)
  8.  
  9. def title(self, obj):
  10. return "Police beat central: Crimes for beat %s" % obj.beat
  11.  
  12. def link(self, obj):
  13. return obj.get_absolute_url()
  14.  
  15. def description(self, obj):
  16. return "Crimes recently reported in police beat %s" % obj.beat
  17.  
  18. def items(self, obj):
  19. return Crime.objects.filter(beat=obj).order_by('-crime_date')[:30]

To generate the feed’s <title>, <link> and <description>, Djangouses the title(), link() and description() methods. Inthe previous example, they were string class attributes, but this exampleillustrates that they can be either strings or methods. For each oftitle, link and description, Django follows thisalgorithm:

  • First, it tries to call a method, passing the obj argument, whereobj 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, ittries items(obj), then items(), then finally an itemsclass attribute (which should be a list).

We are using a template for the item descriptions. It can be as minimal asthis:

  1. {{ obj.description }}

However, you are free to add formatting as desired.

The ExampleFeed class below gives full documentation on methods andattributes 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 yourFeed class, like so:

  1. from django.utils.feedgenerator import Atom1Feed
  2.  
  3. class MyFeed(Feed):
  4. 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 theitem_enclosures hook or, alternatively and if you only have a singleenclosure per item, the item_enclosure_url, item_enclosure_length, anditem_enclosure_mime_type hooks. See the ExampleFeed class below forusage examples.

Language

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

Changed in Django 3.0:The language class attribute was added. In older versions, the behavioris the same as language = settings.LANGUAGE_CODE.

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/&#34;). If link doesn’t return the domain,the syndication framework will insert the domain of the current site, accordingto your SITE_ID setting.

Atom feeds require a <link rel="self"> that defines the feed’s currentlocation. The syndication framework populates this automatically, using thedomain 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 theirfeeds. To do that, you can create a subclass of yourFeed class and set the feed_typeto 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.  
  5. class RssSiteNewsFeed(Feed):
  6. title = "Police beat site news"
  7. link = "/sitenews/"
  8. description = "Updates on changes and additions to police beat central."
  9.  
  10. def items(self):
  11. return NewsItem.objects.order_by('-pub_date')[:5]
  12.  
  13. class AtomSiteNewsFeed(RssSiteNewsFeed):
  14. feed_type = Atom1Feed
  15. subtitle = RssSiteNewsFeed.description

Note

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

If you provide a description in yourFeed class, Django will _not_automatically put that into the subtitle element, because asubtitle and description are not necessarily the same thing. Instead, youshould define a subtitle attribute.

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

And the accompanying URLconf:

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

Feed class reference

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

The low-level framework

Behind the scenes, the high-level RSS framework uses a lower-level frameworkfor 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 canalso create custom feed generator subclasses for use with the feed_typeFeed option.

SyndicationFeed classes

The feedgenerator module contains a base class:

All parameters should be strings, except categories, which should be asequence of strings. Beware that some control charactersare not allowedin XML documents. If your content has some of them, you might encounter aValueError when producing the feed.

Required keyword arguments are:

  • title
  • link
  • descriptionOptional keyword arguments are:

  • author_email

  • author_name
  • author_link
  • pubdate
  • comments
  • unique_id
  • enclosures
  • categories
  • item_copyright
  • ttl
  • updateddateExtra keyword arguments will be stored for custom feed generators.

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

  1. >>> from django.utils import feedgenerator
  2. >>> from datetime import datetime
  3. >>> f = feedgenerator.Atom1Feed(
  4. ... title="My Weblog",
  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 subclassSyndicationFeed and completely replace the write() andwriteString() methods.

However, if the feed format is a spin-off of RSS or Atom (i.e. GeoRSS, Apple’siTunes podcast format, etc.), you’ve got a better choice. These types offeeds typically add extra elements and/or attributes to the underlying format,and there are a set of methods that SyndicationFeed calls to get these extraattributes. 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 anXMLGenerator 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 toSyndicationFeed.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 methodssince 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.  
  7. def add_root_elements(self, handler):
  8. super().add_root_elements(handler)
  9. handler.addQuickElement('itunes:explicit', 'clean')

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