The syndication feed framework

    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 feed-generating framework is supplied by the Feed class. To create a feed, write a 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 . They can live anywhere in your codebase.

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

    A simple example

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

    To connect a URL to this feed, put an instance of the Feed object in your . 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 , 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 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 class. The templates are rendered for each item and are passed two template context variables:

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

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

    1. {{ obj.description }}

    However, you are free to add formatting as desired.

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

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

    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:

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

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

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

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

    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:

    • pubdate should be a Python object.
    • updateddate should be a Python datetime object.
    • enclosures should be a list of instances.
    • categories should be a sequence of strings.

    SyndicationFeed.write()

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

    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. , 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 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:

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