The syndication feed framework

Django comes with a high-level syndication-feed-generating frameworkthat makes creating RSS and Atom feeds easy.

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, simply, a method that returns a list of objects thatshould be included in the feed as <item> elements. Although thisexample returns NewsItem objects using Django'sobject-relational mapper, items()doesn't have to return model instances. Although you get a few bits offunctionality "for free" by using Django models, items() canreturn 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 simple 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 very simple:

  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). Thiscomes directly from your LANGUAGE_CODE setting.

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. That's easy to do with Django: Just create a subclass of yourFeedclass and set the feed_type to something different. Then update yourURLconf 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

注解

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

  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.

警告

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

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