syndication.txt 38 KB

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