1. ==============================
    
  2. The syndication feed framework
    
  3. ==============================
    
  4. 
    
  5. .. module:: django.contrib.syndication
    
  6.    :synopsis: A framework for generating syndication feeds, in RSS and Atom,
    
  7.               quite easily.
    
  8. 
    
  9. Django comes with a high-level syndication-feed-generating framework for
    
  10. creating RSS_ and :rfc:`Atom <4287>` feeds.
    
  11. 
    
  12. To create any syndication feed, all you have to do is write a short
    
  13. Python class. You can create as many feeds as you want.
    
  14. 
    
  15. Django also comes with a lower-level feed-generating API. Use this if
    
  16. you want to generate feeds outside of a web context, or in some other
    
  17. lower-level way.
    
  18. 
    
  19. .. _RSS: https://developer.mozilla.org/en-US/docs/Glossary/RSS
    
  20. 
    
  21. The high-level framework
    
  22. ========================
    
  23. 
    
  24. Overview
    
  25. --------
    
  26. 
    
  27. The high-level feed-generating framework is supplied by the
    
  28. :class:`~django.contrib.syndication.views.Feed` class. To create a
    
  29. feed, write a :class:`~django.contrib.syndication.views.Feed` class
    
  30. and point to an instance of it in your :doc:`URLconf
    
  31. </topics/http/urls>`.
    
  32. 
    
  33. ``Feed`` classes
    
  34. ----------------
    
  35. 
    
  36. A :class:`~django.contrib.syndication.views.Feed` class is a Python
    
  37. class that represents a syndication feed. A feed can be simple (e.g.,
    
  38. a "site news" feed, or a basic feed displaying the latest entries of a
    
  39. blog) or more complex (e.g., a feed displaying all the blog entries in
    
  40. a particular category, where the category is variable).
    
  41. 
    
  42. Feed classes subclass :class:`django.contrib.syndication.views.Feed`.
    
  43. They can live anywhere in your codebase.
    
  44. 
    
  45. Instances of :class:`~django.contrib.syndication.views.Feed` classes
    
  46. are views which can be used in your :doc:`URLconf </topics/http/urls>`.
    
  47. 
    
  48. A simple example
    
  49. ----------------
    
  50. 
    
  51. This simple example, taken from a hypothetical police beat news site describes
    
  52. a feed of the latest five news items::
    
  53. 
    
  54.     from django.contrib.syndication.views import Feed
    
  55.     from django.urls import reverse
    
  56.     from policebeat.models import NewsItem
    
  57. 
    
  58.     class LatestEntriesFeed(Feed):
    
  59.         title = "Police beat site news"
    
  60.         link = "/sitenews/"
    
  61.         description = "Updates on changes and additions to police beat central."
    
  62. 
    
  63.         def items(self):
    
  64.             return NewsItem.objects.order_by('-pub_date')[:5]
    
  65. 
    
  66.         def item_title(self, item):
    
  67.             return item.title
    
  68. 
    
  69.         def item_description(self, item):
    
  70.             return item.description
    
  71. 
    
  72.         # item_link is only needed if NewsItem has no get_absolute_url method.
    
  73.         def item_link(self, item):
    
  74.             return reverse('news-item', args=[item.pk])
    
  75. 
    
  76. To connect a URL to this feed, put an instance of the Feed object in
    
  77. your :doc:`URLconf </topics/http/urls>`. For example::
    
  78. 
    
  79.     from django.urls import path
    
  80.     from myproject.feeds import LatestEntriesFeed
    
  81. 
    
  82.     urlpatterns = [
    
  83.         # ...
    
  84.         path('latest/feed/', LatestEntriesFeed()),
    
  85.         # ...
    
  86.     ]
    
  87. 
    
  88. Note:
    
  89. 
    
  90. * The Feed class subclasses :class:`django.contrib.syndication.views.Feed`.
    
  91. 
    
  92. * ``title``, ``link`` and ``description`` correspond to the
    
  93.   standard RSS ``<title>``, ``<link>`` and ``<description>`` elements,
    
  94.   respectively.
    
  95. 
    
  96. * ``items()`` is, a method that returns a list of objects that should be
    
  97.   included in the feed as ``<item>`` elements. Although this example returns
    
  98.   ``NewsItem`` objects using Django's :doc:`object-relational mapper
    
  99.   </ref/models/querysets>`, ``items()`` doesn't have to return model instances.
    
  100.   Although you get a few bits of functionality "for free" by using Django
    
  101.   models, ``items()`` can return any type of object you want.
    
  102. 
    
  103. * If you're creating an Atom feed, rather than an RSS feed, set the
    
  104.   ``subtitle`` attribute instead of the ``description`` attribute.
    
  105.   See `Publishing Atom and RSS feeds in tandem`_, later, for an example.
    
  106. 
    
  107. One thing is left to do. In an RSS feed, each ``<item>`` has a ``<title>``,
    
  108. ``<link>`` and ``<description>``. We need to tell the framework what data to put
    
  109. into those elements.
    
  110. 
    
  111. * For the contents of ``<title>`` and ``<description>``, Django tries
    
  112.   calling the methods ``item_title()`` and ``item_description()`` on
    
  113.   the :class:`~django.contrib.syndication.views.Feed` class. They are passed
    
  114.   a single parameter, ``item``, which is the object itself. These are
    
  115.   optional; by default, the string representation of the object is used for
    
  116.   both.
    
  117. 
    
  118.   If you want to do any special formatting for either the title or
    
  119.   description, :doc:`Django templates </ref/templates/language>` can be used
    
  120.   instead. Their paths can be specified with the ``title_template`` and
    
  121.   ``description_template`` attributes on the
    
  122.   :class:`~django.contrib.syndication.views.Feed` class. The templates are
    
  123.   rendered for each item and are passed two template context variables:
    
  124. 
    
  125.   * ``{{ obj }}`` -- The current object (one of whichever objects you
    
  126.     returned in ``items()``).
    
  127. 
    
  128.   * ``{{ site }}`` -- A :class:`django.contrib.sites.models.Site` object
    
  129.     representing the current site. This is useful for ``{{ site.domain
    
  130.     }}`` or ``{{ site.name }}``. If you do *not* have the Django sites
    
  131.     framework installed, this will be set to a
    
  132.     :class:`~django.contrib.sites.requests.RequestSite` object. See the
    
  133.     :ref:`RequestSite section of the sites framework documentation
    
  134.     <requestsite-objects>` for more.
    
  135. 
    
  136.   See `a complex example`_ below that uses a description template.
    
  137. 
    
  138.   .. method:: Feed.get_context_data(**kwargs)
    
  139. 
    
  140.       There is also a way to pass additional information to title and description
    
  141.       templates, if you need to supply more than the two variables mentioned
    
  142.       before. You can provide your implementation of ``get_context_data`` method
    
  143.       in your ``Feed`` subclass. For example::
    
  144. 
    
  145.         from mysite.models import Article
    
  146.         from django.contrib.syndication.views import Feed
    
  147. 
    
  148.         class ArticlesFeed(Feed):
    
  149.             title = "My articles"
    
  150.             description_template = "feeds/articles.html"
    
  151. 
    
  152.             def items(self):
    
  153.                 return Article.objects.order_by('-pub_date')[:5]
    
  154. 
    
  155.             def get_context_data(self, **kwargs):
    
  156.                 context = super().get_context_data(**kwargs)
    
  157.                 context['foo'] = 'bar'
    
  158.                 return context
    
  159. 
    
  160.   And the template:
    
  161. 
    
  162.   .. code-block:: html+django
    
  163. 
    
  164.     Something about {{ foo }}: {{ obj.description }}
    
  165. 
    
  166.   This method will be called once per each item in the list returned by
    
  167.   ``items()`` with the following keyword arguments:
    
  168. 
    
  169.   * ``item``: the current item. For backward compatibility reasons, the name
    
  170.     of this context variable is ``{{ obj }}``.
    
  171. 
    
  172.   * ``obj``: the object returned by ``get_object()``. By default this is not
    
  173.     exposed to the templates to avoid confusion with ``{{ obj }}`` (see above),
    
  174.     but you can use it in your implementation of ``get_context_data()``.
    
  175. 
    
  176.   * ``site``: current site as described above.
    
  177. 
    
  178.   * ``request``: current request.
    
  179. 
    
  180.   The behavior of ``get_context_data()`` mimics that of
    
  181.   :ref:`generic views <adding-extra-context>` - you're supposed to call
    
  182.   ``super()`` to retrieve context data from parent class, add your data
    
  183.   and return the modified dictionary.
    
  184. 
    
  185. * To specify the contents of ``<link>``, you have two options. For each item
    
  186.   in ``items()``, Django first tries calling the
    
  187.   ``item_link()`` method on the
    
  188.   :class:`~django.contrib.syndication.views.Feed` class. In a similar way to
    
  189.   the title and description, it is passed it a single parameter,
    
  190.   ``item``. If that method doesn't exist, Django tries executing a
    
  191.   ``get_absolute_url()`` method on that object. Both
    
  192.   ``get_absolute_url()`` and ``item_link()`` should return the
    
  193.   item's URL as a normal Python string. As with ``get_absolute_url()``, the
    
  194.   result of ``item_link()`` will be included directly in the URL, so you
    
  195.   are responsible for doing all necessary URL quoting and conversion to
    
  196.   ASCII inside the method itself.
    
  197. 
    
  198. A complex example
    
  199. -----------------
    
  200. 
    
  201. The framework also supports more complex feeds, via arguments.
    
  202. 
    
  203. For example, a website could offer an RSS feed of recent crimes for every
    
  204. police beat in a city. It'd be silly to create a separate
    
  205. :class:`~django.contrib.syndication.views.Feed` class for each police beat; that
    
  206. would violate the :ref:`DRY principle <dry>` and would couple data to
    
  207. programming logic. Instead, the syndication framework lets you access the
    
  208. arguments passed from your :doc:`URLconf </topics/http/urls>` so feeds can output
    
  209. items based on information in the feed's URL.
    
  210. 
    
  211. The police beat feeds could be accessible via URLs like this:
    
  212. 
    
  213. * :file:`/beats/613/rss/` -- Returns recent crimes for beat 613.
    
  214. * :file:`/beats/1424/rss/` -- Returns recent crimes for beat 1424.
    
  215. 
    
  216. These can be matched with a :doc:`URLconf </topics/http/urls>` line such as::
    
  217. 
    
  218.     path('beats/<int:beat_id>/rss/', BeatFeed()),
    
  219. 
    
  220. Like a view, the arguments in the URL are passed to the ``get_object()``
    
  221. method along with the request object.
    
  222. 
    
  223. Here's the code for these beat-specific feeds::
    
  224. 
    
  225.     from django.contrib.syndication.views import Feed
    
  226. 
    
  227.     class BeatFeed(Feed):
    
  228.         description_template = 'feeds/beat_description.html'
    
  229. 
    
  230.         def get_object(self, request, beat_id):
    
  231.             return Beat.objects.get(pk=beat_id)
    
  232. 
    
  233.         def title(self, obj):
    
  234.             return "Police beat central: Crimes for beat %s" % obj.beat
    
  235. 
    
  236.         def link(self, obj):
    
  237.             return obj.get_absolute_url()
    
  238. 
    
  239.         def description(self, obj):
    
  240.             return "Crimes recently reported in police beat %s" % obj.beat
    
  241. 
    
  242.         def items(self, obj):
    
  243.             return Crime.objects.filter(beat=obj).order_by('-crime_date')[:30]
    
  244. 
    
  245. To generate the feed's ``<title>``, ``<link>`` and ``<description>``, Django
    
  246. uses the ``title()``, ``link()`` and ``description()`` methods. In
    
  247. the previous example, they were string class attributes, but this example
    
  248. illustrates that they can be either strings *or* methods. For each of
    
  249. ``title``, ``link`` and ``description``, Django follows this
    
  250. algorithm:
    
  251. 
    
  252. * First, it tries to call a method, passing the ``obj`` argument, where
    
  253.   ``obj`` is the object returned by ``get_object()``.
    
  254. 
    
  255. * Failing that, it tries to call a method with no arguments.
    
  256. 
    
  257. * Failing that, it uses the class attribute.
    
  258. 
    
  259. Also note that ``items()`` also follows the same algorithm -- first, it
    
  260. tries ``items(obj)``, then ``items()``, then finally an ``items``
    
  261. class attribute (which should be a list).
    
  262. 
    
  263. We are using a template for the item descriptions. It can be as minimal as
    
  264. this:
    
  265. 
    
  266. .. code-block:: html+django
    
  267. 
    
  268.     {{ obj.description }}
    
  269. 
    
  270. However, you are free to add formatting as desired.
    
  271. 
    
  272. The ``ExampleFeed`` class below gives full documentation on methods and
    
  273. attributes of :class:`~django.contrib.syndication.views.Feed` classes.
    
  274. 
    
  275. Specifying the type of feed
    
  276. ---------------------------
    
  277. 
    
  278. By default, feeds produced in this framework use RSS 2.0.
    
  279. 
    
  280. To change that, add a ``feed_type`` attribute to your
    
  281. :class:`~django.contrib.syndication.views.Feed` class, like so::
    
  282. 
    
  283.     from django.utils.feedgenerator import Atom1Feed
    
  284. 
    
  285.     class MyFeed(Feed):
    
  286.         feed_type = Atom1Feed
    
  287. 
    
  288. Note that you set ``feed_type`` to a class object, not an instance.
    
  289. 
    
  290. Currently available feed types are:
    
  291. 
    
  292. * :class:`django.utils.feedgenerator.Rss201rev2Feed` (RSS 2.01. Default.)
    
  293. * :class:`django.utils.feedgenerator.RssUserland091Feed` (RSS 0.91.)
    
  294. * :class:`django.utils.feedgenerator.Atom1Feed` (Atom 1.0.)
    
  295. 
    
  296. Enclosures
    
  297. ----------
    
  298. 
    
  299. To specify enclosures, such as those used in creating podcast feeds, use the
    
  300. ``item_enclosures`` hook or, alternatively and if you only have a single
    
  301. enclosure per item, the ``item_enclosure_url``, ``item_enclosure_length``, and
    
  302. ``item_enclosure_mime_type`` hooks. See the ``ExampleFeed`` class below for
    
  303. usage examples.
    
  304. 
    
  305. Language
    
  306. --------
    
  307. 
    
  308. Feeds created by the syndication framework automatically include the
    
  309. appropriate ``<language>`` tag (RSS 2.0) or ``xml:lang`` attribute (Atom). By
    
  310. default, this is :func:`django.utils.translation.get_language()`. You can change it
    
  311. by setting the ``language`` class attribute.
    
  312. 
    
  313. URLs
    
  314. ----
    
  315. 
    
  316. The ``link`` method/attribute can return either an absolute path (e.g.
    
  317. :file:`"/blog/"`) or a URL with the fully-qualified domain and protocol (e.g.
    
  318. ``"https://www.example.com/blog/"``). If ``link`` doesn't return the domain,
    
  319. the syndication framework will insert the domain of the current site, according
    
  320. to your :setting:`SITE_ID setting <SITE_ID>`.
    
  321. 
    
  322. Atom feeds require a ``<link rel="self">`` that defines the feed's current
    
  323. location. The syndication framework populates this automatically, using the
    
  324. domain of the current site according to the :setting:`SITE_ID` setting.
    
  325. 
    
  326. Publishing Atom and RSS feeds in tandem
    
  327. ---------------------------------------
    
  328. 
    
  329. Some developers like to make available both Atom *and* RSS versions of their
    
  330. feeds. To do that, you can create a subclass of your
    
  331. :class:`~django.contrib.syndication.views.Feed` class and set the ``feed_type``
    
  332. to something different. Then update your URLconf to add the extra versions.
    
  333. 
    
  334. Here's a full example::
    
  335. 
    
  336.     from django.contrib.syndication.views import Feed
    
  337.     from policebeat.models import NewsItem
    
  338.     from django.utils.feedgenerator import Atom1Feed
    
  339. 
    
  340.     class RssSiteNewsFeed(Feed):
    
  341.         title = "Police beat site news"
    
  342.         link = "/sitenews/"
    
  343.         description = "Updates on changes and additions to police beat central."
    
  344. 
    
  345.         def items(self):
    
  346.             return NewsItem.objects.order_by('-pub_date')[:5]
    
  347. 
    
  348.     class AtomSiteNewsFeed(RssSiteNewsFeed):
    
  349.         feed_type = Atom1Feed
    
  350.         subtitle = RssSiteNewsFeed.description
    
  351. 
    
  352. .. Note::
    
  353.     In this example, the RSS feed uses a ``description`` while the Atom
    
  354.     feed uses a ``subtitle``. That's because Atom feeds don't provide for
    
  355.     a feed-level "description," but they *do* provide for a "subtitle."
    
  356. 
    
  357.     If you provide a ``description`` in your
    
  358.     :class:`~django.contrib.syndication.views.Feed` class, Django will *not*
    
  359.     automatically put that into the ``subtitle`` element, because a
    
  360.     subtitle and description are not necessarily the same thing. Instead, you
    
  361.     should define a ``subtitle`` attribute.
    
  362. 
    
  363.     In the above example, we set the Atom feed's ``subtitle`` to the RSS feed's
    
  364.     ``description``, because it's quite short already.
    
  365. 
    
  366. And the accompanying URLconf::
    
  367. 
    
  368.     from django.urls import path
    
  369.     from myproject.feeds import AtomSiteNewsFeed, RssSiteNewsFeed
    
  370. 
    
  371.     urlpatterns = [
    
  372.         # ...
    
  373.         path('sitenews/rss/', RssSiteNewsFeed()),
    
  374.         path('sitenews/atom/', AtomSiteNewsFeed()),
    
  375.         # ...
    
  376.     ]
    
  377. 
    
  378. ``Feed`` class reference
    
  379. ------------------------
    
  380. 
    
  381. .. class:: views.Feed
    
  382. 
    
  383. This example illustrates all possible attributes and methods for a
    
  384. :class:`~django.contrib.syndication.views.Feed` class::
    
  385. 
    
  386.     from django.contrib.syndication.views import Feed
    
  387.     from django.utils import feedgenerator
    
  388. 
    
  389.     class ExampleFeed(Feed):
    
  390. 
    
  391.         # FEED TYPE -- Optional. This should be a class that subclasses
    
  392.         # django.utils.feedgenerator.SyndicationFeed. This designates
    
  393.         # which type of feed this should be: RSS 2.0, Atom 1.0, etc. If
    
  394.         # you don't specify feed_type, your feed will be RSS 2.0. This
    
  395.         # should be a class, not an instance of the class.
    
  396. 
    
  397.         feed_type = feedgenerator.Rss201rev2Feed
    
  398. 
    
  399.         # TEMPLATE NAMES -- Optional. These should be strings
    
  400.         # representing names of Django templates that the system should
    
  401.         # use in rendering the title and description of your feed items.
    
  402.         # Both are optional. If a template is not specified, the
    
  403.         # item_title() or item_description() methods are used instead.
    
  404. 
    
  405.         title_template = None
    
  406.         description_template = None
    
  407. 
    
  408.         # LANGUAGE -- Optional. This should be a string specifying a language
    
  409.         # code. Defaults to django.utils.translation.get_language().
    
  410.         language = 'de'
    
  411. 
    
  412.         # TITLE -- One of the following three is required. The framework
    
  413.         # looks for them in this order.
    
  414. 
    
  415.         def title(self, obj):
    
  416.             """
    
  417.             Takes the object returned by get_object() and returns the
    
  418.             feed's title as a normal Python string.
    
  419.             """
    
  420. 
    
  421.         def title(self):
    
  422.             """
    
  423.             Returns the feed's title as a normal Python string.
    
  424.             """
    
  425. 
    
  426.         title = 'foo' # Hard-coded title.
    
  427. 
    
  428.         # LINK -- One of the following three is required. The framework
    
  429.         # looks for them in this order.
    
  430. 
    
  431.         def link(self, obj):
    
  432.             """
    
  433.             # Takes the object returned by get_object() and returns the URL
    
  434.             # of the HTML version of the feed as a normal Python string.
    
  435.             """
    
  436. 
    
  437.         def link(self):
    
  438.             """
    
  439.             Returns the URL of the HTML version of the feed as a normal Python
    
  440.             string.
    
  441.             """
    
  442. 
    
  443.         link = '/blog/' # Hard-coded URL.
    
  444. 
    
  445.         # FEED_URL -- One of the following three is optional. The framework
    
  446.         # looks for them in this order.
    
  447. 
    
  448.         def feed_url(self, obj):
    
  449.             """
    
  450.             # Takes the object returned by get_object() and returns the feed's
    
  451.             # own URL as a normal Python string.
    
  452.             """
    
  453. 
    
  454.         def feed_url(self):
    
  455.             """
    
  456.             Returns the feed's own URL as a normal Python string.
    
  457.             """
    
  458. 
    
  459.         feed_url = '/blog/rss/' # Hard-coded URL.
    
  460. 
    
  461.         # GUID -- One of the following three is optional. The framework looks
    
  462.         # for them in this order. This property is only used for Atom feeds
    
  463.         # (where it is the feed-level ID element). If not provided, the feed
    
  464.         # link is used as the ID.
    
  465. 
    
  466.         def feed_guid(self, obj):
    
  467.             """
    
  468.             Takes the object returned by get_object() and returns the globally
    
  469.             unique ID for the feed as a normal Python string.
    
  470.             """
    
  471. 
    
  472.         def feed_guid(self):
    
  473.             """
    
  474.             Returns the feed's globally unique ID as a normal Python string.
    
  475.             """
    
  476. 
    
  477.         feed_guid = '/foo/bar/1234' # Hard-coded guid.
    
  478. 
    
  479.         # DESCRIPTION -- One of the following three is required. The framework
    
  480.         # looks for them in this order.
    
  481. 
    
  482.         def description(self, obj):
    
  483.             """
    
  484.             Takes the object returned by get_object() and returns the feed's
    
  485.             description as a normal Python string.
    
  486.             """
    
  487. 
    
  488.         def description(self):
    
  489.             """
    
  490.             Returns the feed's description as a normal Python string.
    
  491.             """
    
  492. 
    
  493.         description = 'Foo bar baz.' # Hard-coded description.
    
  494. 
    
  495.         # AUTHOR NAME --One of the following three is optional. The framework
    
  496.         # looks for them in this order.
    
  497. 
    
  498.         def author_name(self, obj):
    
  499.             """
    
  500.             Takes the object returned by get_object() and returns the feed's
    
  501.             author's name as a normal Python string.
    
  502.             """
    
  503. 
    
  504.         def author_name(self):
    
  505.             """
    
  506.             Returns the feed's author's name as a normal Python string.
    
  507.             """
    
  508. 
    
  509.         author_name = 'Sally Smith' # Hard-coded author name.
    
  510. 
    
  511.         # AUTHOR EMAIL --One of the following three is optional. The framework
    
  512.         # looks for them in this order.
    
  513. 
    
  514.         def author_email(self, obj):
    
  515.             """
    
  516.             Takes the object returned by get_object() and returns the feed's
    
  517.             author's email as a normal Python string.
    
  518.             """
    
  519. 
    
  520.         def author_email(self):
    
  521.             """
    
  522.             Returns the feed's author's email as a normal Python string.
    
  523.             """
    
  524. 
    
  525.         author_email = '[email protected]' # Hard-coded author email.
    
  526. 
    
  527.         # AUTHOR LINK --One of the following three is optional. The framework
    
  528.         # looks for them in this order. In each case, the URL should include
    
  529.         # the "http://" and domain name.
    
  530. 
    
  531.         def author_link(self, obj):
    
  532.             """
    
  533.             Takes the object returned by get_object() and returns the feed's
    
  534.             author's URL as a normal Python string.
    
  535.             """
    
  536. 
    
  537.         def author_link(self):
    
  538.             """
    
  539.             Returns the feed's author's URL as a normal Python string.
    
  540.             """
    
  541. 
    
  542.         author_link = 'https://www.example.com/' # Hard-coded author URL.
    
  543. 
    
  544.         # CATEGORIES -- One of the following three is optional. The framework
    
  545.         # looks for them in this order. In each case, the method/attribute
    
  546.         # should return an iterable object that returns strings.
    
  547. 
    
  548.         def categories(self, obj):
    
  549.             """
    
  550.             Takes the object returned by get_object() and returns the feed's
    
  551.             categories as iterable over strings.
    
  552.             """
    
  553. 
    
  554.         def categories(self):
    
  555.             """
    
  556.             Returns the feed's categories as iterable over strings.
    
  557.             """
    
  558. 
    
  559.         categories = ("python", "django") # Hard-coded list of categories.
    
  560. 
    
  561.         # COPYRIGHT NOTICE -- One of the following three is optional. The
    
  562.         # framework looks for them in this order.
    
  563. 
    
  564.         def feed_copyright(self, obj):
    
  565.             """
    
  566.             Takes the object returned by get_object() and returns the feed's
    
  567.             copyright notice as a normal Python string.
    
  568.             """
    
  569. 
    
  570.         def feed_copyright(self):
    
  571.             """
    
  572.             Returns the feed's copyright notice as a normal Python string.
    
  573.             """
    
  574. 
    
  575.         feed_copyright = 'Copyright (c) 2007, Sally Smith' # Hard-coded copyright notice.
    
  576. 
    
  577.         # TTL -- One of the following three is optional. The framework looks
    
  578.         # for them in this order. Ignored for Atom feeds.
    
  579. 
    
  580.         def ttl(self, obj):
    
  581.             """
    
  582.             Takes the object returned by get_object() and returns the feed's
    
  583.             TTL (Time To Live) as a normal Python string.
    
  584.             """
    
  585. 
    
  586.         def ttl(self):
    
  587.             """
    
  588.             Returns the feed's TTL as a normal Python string.
    
  589.             """
    
  590. 
    
  591.         ttl = 600 # Hard-coded Time To Live.
    
  592. 
    
  593.         # ITEMS -- One of the following three is required. The framework looks
    
  594.         # for them in this order.
    
  595. 
    
  596.         def items(self, obj):
    
  597.             """
    
  598.             Takes the object returned by get_object() and returns a list of
    
  599.             items to publish in this feed.
    
  600.             """
    
  601. 
    
  602.         def items(self):
    
  603.             """
    
  604.             Returns a list of items to publish in this feed.
    
  605.             """
    
  606. 
    
  607.         items = ('Item 1', 'Item 2') # Hard-coded items.
    
  608. 
    
  609.         # GET_OBJECT -- This is required for feeds that publish different data
    
  610.         # for different URL parameters. (See "A complex example" above.)
    
  611. 
    
  612.         def get_object(self, request, *args, **kwargs):
    
  613.             """
    
  614.             Takes the current request and the arguments from the URL, and
    
  615.             returns an object represented by this feed. Raises
    
  616.             django.core.exceptions.ObjectDoesNotExist on error.
    
  617.             """
    
  618. 
    
  619.         # ITEM TITLE AND DESCRIPTION -- If title_template or
    
  620.         # description_template are not defined, these are used instead. Both are
    
  621.         # optional, by default they will use the string representation of the
    
  622.         # item.
    
  623. 
    
  624.         def item_title(self, item):
    
  625.             """
    
  626.             Takes an item, as returned by items(), and returns the item's
    
  627.             title as a normal Python string.
    
  628.             """
    
  629. 
    
  630.         def item_title(self):
    
  631.             """
    
  632.             Returns the title for every item in the feed.
    
  633.             """
    
  634. 
    
  635.         item_title = 'Breaking News: Nothing Happening' # Hard-coded title.
    
  636. 
    
  637.         def item_description(self, item):
    
  638.             """
    
  639.             Takes an item, as returned by items(), and returns the item's
    
  640.             description as a normal Python string.
    
  641.             """
    
  642. 
    
  643.         def item_description(self):
    
  644.             """
    
  645.             Returns the description for every item in the feed.
    
  646.             """
    
  647. 
    
  648.         item_description = 'A description of the item.' # Hard-coded description.
    
  649. 
    
  650.         def get_context_data(self, **kwargs):
    
  651.             """
    
  652.             Returns a dictionary to use as extra context if either
    
  653.             description_template or item_template are used.
    
  654. 
    
  655.             Default implementation preserves the old behavior
    
  656.             of using {'obj': item, 'site': current_site} as the context.
    
  657.             """
    
  658. 
    
  659.         # ITEM LINK -- One of these three is required. The framework looks for
    
  660.         # them in this order.
    
  661. 
    
  662.         # First, the framework tries the two methods below, in
    
  663.         # order. Failing that, it falls back to the get_absolute_url()
    
  664.         # method on each item returned by items().
    
  665. 
    
  666.         def item_link(self, item):
    
  667.             """
    
  668.             Takes an item, as returned by items(), and returns the item's URL.
    
  669.             """
    
  670. 
    
  671.         def item_link(self):
    
  672.             """
    
  673.             Returns the URL for every item in the feed.
    
  674.             """
    
  675. 
    
  676.         # ITEM_GUID -- The following method is optional. If not provided, the
    
  677.         # item's link is used by default.
    
  678. 
    
  679.         def item_guid(self, obj):
    
  680.             """
    
  681.             Takes an item, as return by items(), and returns the item's ID.
    
  682.             """
    
  683. 
    
  684.         # ITEM_GUID_IS_PERMALINK -- The following method is optional. If
    
  685.         # provided, it sets the 'isPermaLink' attribute of an item's
    
  686.         # GUID element. This method is used only when 'item_guid' is
    
  687.         # specified.
    
  688. 
    
  689.         def item_guid_is_permalink(self, obj):
    
  690.             """
    
  691.             Takes an item, as returned by items(), and returns a boolean.
    
  692.             """
    
  693. 
    
  694.         item_guid_is_permalink = False  # Hard coded value
    
  695. 
    
  696.         # ITEM AUTHOR NAME -- One of the following three is optional. The
    
  697.         # framework looks for them in this order.
    
  698. 
    
  699.         def item_author_name(self, item):
    
  700.             """
    
  701.             Takes an item, as returned by items(), and returns the item's
    
  702.             author's name as a normal Python string.
    
  703.             """
    
  704. 
    
  705.         def item_author_name(self):
    
  706.             """
    
  707.             Returns the author name for every item in the feed.
    
  708.             """
    
  709. 
    
  710.         item_author_name = 'Sally Smith' # Hard-coded author name.
    
  711. 
    
  712.         # ITEM AUTHOR EMAIL --One of the following three is optional. The
    
  713.         # framework looks for them in this order.
    
  714.         #
    
  715.         # If you specify this, you must specify item_author_name.
    
  716. 
    
  717.         def item_author_email(self, obj):
    
  718.             """
    
  719.             Takes an item, as returned by items(), and returns the item's
    
  720.             author's email as a normal Python string.
    
  721.             """
    
  722. 
    
  723.         def item_author_email(self):
    
  724.             """
    
  725.             Returns the author email for every item in the feed.
    
  726.             """
    
  727. 
    
  728.         item_author_email = '[email protected]' # Hard-coded author email.
    
  729. 
    
  730.         # ITEM AUTHOR LINK -- One of the following three is optional. The
    
  731.         # framework looks for them in this order. In each case, the URL should
    
  732.         # include the "http://" and domain name.
    
  733.         #
    
  734.         # If you specify this, you must specify item_author_name.
    
  735. 
    
  736.         def item_author_link(self, obj):
    
  737.             """
    
  738.             Takes an item, as returned by items(), and returns the item's
    
  739.             author's URL as a normal Python string.
    
  740.             """
    
  741. 
    
  742.         def item_author_link(self):
    
  743.             """
    
  744.             Returns the author URL for every item in the feed.
    
  745.             """
    
  746. 
    
  747.         item_author_link = 'https://www.example.com/' # Hard-coded author URL.
    
  748. 
    
  749.         # ITEM ENCLOSURES -- One of the following three is optional. The
    
  750.         # framework looks for them in this order. If one of them is defined,
    
  751.         # ``item_enclosure_url``, ``item_enclosure_length``, and
    
  752.         # ``item_enclosure_mime_type`` will have no effect.
    
  753. 
    
  754.         def item_enclosures(self, item):
    
  755.             """
    
  756.             Takes an item, as returned by items(), and returns a list of
    
  757.             ``django.utils.feedgenerator.Enclosure`` objects.
    
  758.             """
    
  759. 
    
  760.         def item_enclosures(self):
    
  761.             """
    
  762.             Returns the ``django.utils.feedgenerator.Enclosure`` list for every
    
  763.             item in the feed.
    
  764.             """
    
  765. 
    
  766.         item_enclosures = []  # Hard-coded enclosure list
    
  767. 
    
  768.         # ITEM ENCLOSURE URL -- One of these three is required if you're
    
  769.         # publishing enclosures and you're not using ``item_enclosures``. The
    
  770.         # framework looks for them in this order.
    
  771. 
    
  772.         def item_enclosure_url(self, item):
    
  773.             """
    
  774.             Takes an item, as returned by items(), and returns the item's
    
  775.             enclosure URL.
    
  776.             """
    
  777. 
    
  778.         def item_enclosure_url(self):
    
  779.             """
    
  780.             Returns the enclosure URL for every item in the feed.
    
  781.             """
    
  782. 
    
  783.         item_enclosure_url = "/foo/bar.mp3" # Hard-coded enclosure link.
    
  784. 
    
  785.         # ITEM ENCLOSURE LENGTH -- One of these three is required if you're
    
  786.         # publishing enclosures and you're not using ``item_enclosures``. The
    
  787.         # framework looks for them in this order. In each case, the returned
    
  788.         # value should be either an integer, or a string representation of the
    
  789.         # integer, in bytes.
    
  790. 
    
  791.         def item_enclosure_length(self, item):
    
  792.             """
    
  793.             Takes an item, as returned by items(), and returns the item's
    
  794.             enclosure length.
    
  795.             """
    
  796. 
    
  797.         def item_enclosure_length(self):
    
  798.             """
    
  799.             Returns the enclosure length for every item in the feed.
    
  800.             """
    
  801. 
    
  802.         item_enclosure_length = 32000 # Hard-coded enclosure length.
    
  803. 
    
  804.         # ITEM ENCLOSURE MIME TYPE -- One of these three is required if you're
    
  805.         # publishing enclosures and you're not using ``item_enclosures``. The
    
  806.         # framework looks for them in this order.
    
  807. 
    
  808.         def item_enclosure_mime_type(self, item):
    
  809.             """
    
  810.             Takes an item, as returned by items(), and returns the item's
    
  811.             enclosure MIME type.
    
  812.             """
    
  813. 
    
  814.         def item_enclosure_mime_type(self):
    
  815.             """
    
  816.             Returns the enclosure MIME type for every item in the feed.
    
  817.             """
    
  818. 
    
  819.         item_enclosure_mime_type = "audio/mpeg" # Hard-coded enclosure MIME type.
    
  820. 
    
  821.         # ITEM PUBDATE -- It's optional to use one of these three. This is a
    
  822.         # hook that specifies how to get the pubdate for a given item.
    
  823.         # In each case, the method/attribute should return a Python
    
  824.         # datetime.datetime object.
    
  825. 
    
  826.         def item_pubdate(self, item):
    
  827.             """
    
  828.             Takes an item, as returned by items(), and returns the item's
    
  829.             pubdate.
    
  830.             """
    
  831. 
    
  832.         def item_pubdate(self):
    
  833.             """
    
  834.             Returns the pubdate for every item in the feed.
    
  835.             """
    
  836. 
    
  837.         item_pubdate = datetime.datetime(2005, 5, 3) # Hard-coded pubdate.
    
  838. 
    
  839.         # ITEM UPDATED -- It's optional to use one of these three. This is a
    
  840.         # hook that specifies how to get the updateddate for a given item.
    
  841.         # In each case, the method/attribute should return a Python
    
  842.         # datetime.datetime object.
    
  843. 
    
  844.         def item_updateddate(self, item):
    
  845.             """
    
  846.             Takes an item, as returned by items(), and returns the item's
    
  847.             updateddate.
    
  848.             """
    
  849. 
    
  850.         def item_updateddate(self):
    
  851.             """
    
  852.             Returns the updateddate for every item in the feed.
    
  853.             """
    
  854. 
    
  855.         item_updateddate = datetime.datetime(2005, 5, 3) # Hard-coded updateddate.
    
  856. 
    
  857.         # ITEM CATEGORIES -- It's optional to use one of these three. This is
    
  858.         # a hook that specifies how to get the list of categories for a given
    
  859.         # item. In each case, the method/attribute should return an iterable
    
  860.         # object that returns strings.
    
  861. 
    
  862.         def item_categories(self, item):
    
  863.             """
    
  864.             Takes an item, as returned by items(), and returns the item's
    
  865.             categories.
    
  866.             """
    
  867. 
    
  868.         def item_categories(self):
    
  869.             """
    
  870.             Returns the categories for every item in the feed.
    
  871.             """
    
  872. 
    
  873.         item_categories = ("python", "django") # Hard-coded categories.
    
  874. 
    
  875.         # ITEM COPYRIGHT NOTICE (only applicable to Atom feeds) -- One of the
    
  876.         # following three is optional. The framework looks for them in this
    
  877.         # order.
    
  878. 
    
  879.         def item_copyright(self, obj):
    
  880.             """
    
  881.             Takes an item, as returned by items(), and returns the item's
    
  882.             copyright notice as a normal Python string.
    
  883.             """
    
  884. 
    
  885.         def item_copyright(self):
    
  886.             """
    
  887.             Returns the copyright notice for every item in the feed.
    
  888.             """
    
  889. 
    
  890.         item_copyright = 'Copyright (c) 2007, Sally Smith' # Hard-coded copyright notice.
    
  891. 
    
  892.         # ITEM COMMENTS URL -- It's optional to use one of these three. This is
    
  893.         # a hook that specifies how to get the URL of a page for comments for a
    
  894.         # given item.
    
  895. 
    
  896.         def item_comments(self, obj):
    
  897.             """
    
  898.             Takes an item, as returned by items(), and returns the item's
    
  899.             comments URL as a normal Python string.
    
  900.             """
    
  901. 
    
  902.         def item_comments(self):
    
  903.             """
    
  904.             Returns the comments URL for every item in the feed.
    
  905.             """
    
  906. 
    
  907.         item_comments = 'https://www.example.com/comments' # Hard-coded comments URL
    
  908. 
    
  909. The low-level framework
    
  910. =======================
    
  911. 
    
  912. Behind the scenes, the high-level RSS framework uses a lower-level framework
    
  913. for generating feeds' XML. This framework lives in a single module:
    
  914. :source:`django/utils/feedgenerator.py`.
    
  915. 
    
  916. You use this framework on your own, for lower-level feed generation. You can
    
  917. also create custom feed generator subclasses for use with the ``feed_type``
    
  918. ``Feed`` option.
    
  919. 
    
  920. .. currentmodule:: django.utils.feedgenerator
    
  921. 
    
  922. ``SyndicationFeed`` classes
    
  923. ---------------------------
    
  924. 
    
  925. The :mod:`~django.utils.feedgenerator` module contains a base class:
    
  926. 
    
  927. * :class:`django.utils.feedgenerator.SyndicationFeed`
    
  928. 
    
  929. and several subclasses:
    
  930. 
    
  931. * :class:`django.utils.feedgenerator.RssUserland091Feed`
    
  932. * :class:`django.utils.feedgenerator.Rss201rev2Feed`
    
  933. * :class:`django.utils.feedgenerator.Atom1Feed`
    
  934. 
    
  935. Each of these three classes knows how to render a certain type of feed as XML.
    
  936. They share this interface:
    
  937. 
    
  938. :meth:`.SyndicationFeed.__init__`
    
  939.     Initialize the feed with the given dictionary of metadata, which applies to
    
  940.     the entire feed. Required keyword arguments are:
    
  941. 
    
  942.     * ``title``
    
  943.     * ``link``
    
  944.     * ``description``
    
  945. 
    
  946.     There's also a bunch of other optional keywords:
    
  947. 
    
  948.     * ``language``
    
  949.     * ``author_email``
    
  950.     * ``author_name``
    
  951.     * ``author_link``
    
  952.     * ``subtitle``
    
  953.     * ``categories``
    
  954.     * ``feed_url``
    
  955.     * ``feed_copyright``
    
  956.     * ``feed_guid``
    
  957.     * ``ttl``
    
  958. 
    
  959.     Any extra keyword arguments you pass to ``__init__`` will be stored in
    
  960.     ``self.feed`` for use with `custom feed generators`_.
    
  961. 
    
  962.     All parameters should be strings, except ``categories``, which should be a
    
  963.     sequence of strings. Beware that some control characters
    
  964.     are `not allowed <https://www.w3.org/International/questions/qa-controls>`_
    
  965.     in XML documents. If your content has some of them, you might encounter a
    
  966.     :exc:`ValueError` when producing the feed.
    
  967. 
    
  968. :meth:`.SyndicationFeed.add_item`
    
  969.     Add an item to the feed with the given parameters.
    
  970. 
    
  971.     Required keyword arguments are:
    
  972. 
    
  973.     * ``title``
    
  974.     * ``link``
    
  975.     * ``description``
    
  976. 
    
  977.     Optional keyword arguments are:
    
  978. 
    
  979.     * ``author_email``
    
  980.     * ``author_name``
    
  981.     * ``author_link``
    
  982.     * ``pubdate``
    
  983.     * ``comments``
    
  984.     * ``unique_id``
    
  985.     * ``enclosures``
    
  986.     * ``categories``
    
  987.     * ``item_copyright``
    
  988.     * ``ttl``
    
  989.     * ``updateddate``
    
  990. 
    
  991.     Extra keyword arguments will be stored for `custom feed generators`_.
    
  992. 
    
  993.     All parameters, if given, should be strings, except:
    
  994. 
    
  995.     * ``pubdate`` should be a Python  :class:`~datetime.datetime` object.
    
  996.     * ``updateddate`` should be a Python  :class:`~datetime.datetime` object.
    
  997.     * ``enclosures`` should be a list of
    
  998.       :class:`django.utils.feedgenerator.Enclosure` instances.
    
  999.     * ``categories`` should be a sequence of strings.
    
  1000. 
    
  1001. :meth:`.SyndicationFeed.write`
    
  1002.     Outputs the feed in the given encoding to outfile, which is a file-like object.
    
  1003. 
    
  1004. :meth:`.SyndicationFeed.writeString`
    
  1005.     Returns the feed as a string in the given encoding.
    
  1006. 
    
  1007. For example, to create an Atom 1.0 feed and print it to standard output::
    
  1008. 
    
  1009.     >>> from django.utils import feedgenerator
    
  1010.     >>> from datetime import datetime
    
  1011.     >>> f = feedgenerator.Atom1Feed(
    
  1012.     ...     title="My Blog",
    
  1013.     ...     link="https://www.example.com/",
    
  1014.     ...     description="In which I write about what I ate today.",
    
  1015.     ...     language="en",
    
  1016.     ...     author_name="Myself",
    
  1017.     ...     feed_url="https://example.com/atom.xml")
    
  1018.     >>> f.add_item(title="Hot dog today",
    
  1019.     ...     link="https://www.example.com/entries/1/",
    
  1020.     ...     pubdate=datetime.now(),
    
  1021.     ...     description="<p>Today I had a Vienna Beef hot dog. It was pink, plump and perfect.</p>")
    
  1022.     >>> print(f.writeString('UTF-8'))
    
  1023.     <?xml version="1.0" encoding="UTF-8"?>
    
  1024.     <feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
    
  1025.     ...
    
  1026.     </feed>
    
  1027. 
    
  1028. .. currentmodule:: django.contrib.syndication
    
  1029. 
    
  1030. Custom feed generators
    
  1031. ----------------------
    
  1032. 
    
  1033. If you need to produce a custom feed format, you've got a couple of options.
    
  1034. 
    
  1035. If the feed format is totally custom, you'll want to subclass
    
  1036. ``SyndicationFeed`` and completely replace the ``write()`` and
    
  1037. ``writeString()`` methods.
    
  1038. 
    
  1039. However, if the feed format is a spin-off of RSS or Atom (i.e. GeoRSS_, Apple's
    
  1040. `iTunes podcast format`_, etc.), you've got a better choice. These types of
    
  1041. feeds typically add extra elements and/or attributes to the underlying format,
    
  1042. and there are a set of methods that ``SyndicationFeed`` calls to get these extra
    
  1043. attributes. Thus, you can subclass the appropriate feed generator class
    
  1044. (``Atom1Feed`` or ``Rss201rev2Feed``) and extend these callbacks. They are:
    
  1045. 
    
  1046. .. _georss: https://georss.org
    
  1047. .. _itunes podcast format: https://help.apple.com/itc/podcasts_connect/#/itcb54353390
    
  1048. 
    
  1049. ``SyndicationFeed.root_attributes(self)``
    
  1050.     Return a ``dict`` of attributes to add to the root feed element
    
  1051.     (``feed``/``channel``).
    
  1052. 
    
  1053. ``SyndicationFeed.add_root_elements(self, handler)``
    
  1054.     Callback to add elements inside the root feed element
    
  1055.     (``feed``/``channel``). ``handler`` is an
    
  1056.     :class:`~xml.sax.saxutils.XMLGenerator` from Python's built-in SAX library;
    
  1057.     you'll call methods on it to add to the XML document in process.
    
  1058. 
    
  1059. ``SyndicationFeed.item_attributes(self, item)``
    
  1060.     Return a ``dict`` of attributes to add to each item (``item``/``entry``)
    
  1061.     element. The argument, ``item``, is a dictionary of all the data passed to
    
  1062.     ``SyndicationFeed.add_item()``.
    
  1063. 
    
  1064. ``SyndicationFeed.add_item_elements(self, handler, item)``
    
  1065.     Callback to add elements to each item (``item``/``entry``) element.
    
  1066.     ``handler`` and ``item`` are as above.
    
  1067. 
    
  1068. .. warning::
    
  1069. 
    
  1070.     If you override any of these methods, be sure to call the superclass methods
    
  1071.     since they add the required elements for each feed format.
    
  1072. 
    
  1073. For example, you might start implementing an iTunes RSS feed generator like so::
    
  1074. 
    
  1075.     class iTunesFeed(Rss201rev2Feed):
    
  1076.         def root_attributes(self):
    
  1077.             attrs = super().root_attributes()
    
  1078.             attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
    
  1079.             return attrs
    
  1080. 
    
  1081.         def add_root_elements(self, handler):
    
  1082.             super().add_root_elements(handler)
    
  1083.             handler.addQuickElement('itunes:explicit', 'clean')
    
  1084. 
    
  1085. There's a lot more work to be done for a complete custom feed class, but the
    
  1086. above example should demonstrate the basic idea.