syndication.txt 42 KB

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