syndication.txt 38 KB

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