sitemaps.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. =====================
  2. The sitemap framework
  3. =====================
  4. .. module:: django.contrib.sitemaps
  5. :synopsis: A framework for generating Google sitemap XML files.
  6. Django comes with a high-level sitemap-generating framework to create sitemap_
  7. XML files.
  8. .. _sitemap: https://www.sitemaps.org/
  9. Overview
  10. ========
  11. A sitemap is an XML file on your website that tells search-engine indexers how
  12. frequently your pages change and how "important" certain pages are in relation
  13. to other pages on your site. This information helps search engines index your
  14. site.
  15. The Django sitemap framework automates the creation of this XML file by letting
  16. you express this information in Python code.
  17. It works much like Django's :doc:`syndication framework
  18. </ref/contrib/syndication>`. To create a sitemap, write a
  19. :class:`~django.contrib.sitemaps.Sitemap` class and point to it in your
  20. :doc:`URLconf </topics/http/urls>`.
  21. Installation
  22. ============
  23. To install the sitemap app, follow these steps:
  24. #. Add ``'django.contrib.sitemaps'`` to your :setting:`INSTALLED_APPS` setting.
  25. #. Make sure your :setting:`TEMPLATES` setting contains a ``DjangoTemplates``
  26. backend whose ``APP_DIRS`` options is set to ``True``. It's in there by
  27. default, so you'll only need to change this if you've changed that setting.
  28. #. Make sure you've installed the :mod:`sites framework<django.contrib.sites>`.
  29. (Note: The sitemap application doesn't install any database tables. The only
  30. reason it needs to go into :setting:`INSTALLED_APPS` is so that the
  31. :func:`~django.template.loaders.app_directories.Loader` template
  32. loader can find the default templates.)
  33. Initialization
  34. ==============
  35. .. function:: views.sitemap(request, sitemaps, section=None, template_name='sitemap.xml', content_type='application/xml')
  36. To activate sitemap generation on your Django site, add this line to your
  37. :doc:`URLconf </topics/http/urls>`::
  38. from django.contrib.sitemaps.views import sitemap
  39. path(
  40. "sitemap.xml",
  41. sitemap,
  42. {"sitemaps": sitemaps},
  43. name="django.contrib.sitemaps.views.sitemap",
  44. )
  45. This tells Django to build a sitemap when a client accesses :file:`/sitemap.xml`.
  46. The name of the sitemap file is not important, but the location is. Search
  47. engines will only index links in your sitemap for the current URL level and
  48. below. For instance, if :file:`sitemap.xml` lives in your root directory, it may
  49. reference any URL in your site. However, if your sitemap lives at
  50. :file:`/content/sitemap.xml`, it may only reference URLs that begin with
  51. :file:`/content/`.
  52. The sitemap view takes an extra, required argument: ``{'sitemaps': sitemaps}``.
  53. ``sitemaps`` should be a dictionary that maps a short section label (e.g.,
  54. ``blog`` or ``news``) to its :class:`~django.contrib.sitemaps.Sitemap` class
  55. (e.g., ``BlogSitemap`` or ``NewsSitemap``). It may also map to an *instance* of
  56. a :class:`~django.contrib.sitemaps.Sitemap` class (e.g.,
  57. ``BlogSitemap(some_var)``).
  58. ``Sitemap`` classes
  59. ===================
  60. A :class:`~django.contrib.sitemaps.Sitemap` class is a Python class that
  61. represents a "section" of entries in your sitemap. For example, one
  62. :class:`~django.contrib.sitemaps.Sitemap` class could represent all the entries
  63. of your blog, while another could represent all of the events in your events
  64. calendar.
  65. In the simplest case, all these sections get lumped together into one
  66. :file:`sitemap.xml`, but it's also possible to use the framework to generate a
  67. sitemap index that references individual sitemap files, one per section. (See
  68. `Creating a sitemap index`_ below.)
  69. :class:`~django.contrib.sitemaps.Sitemap` classes must subclass
  70. ``django.contrib.sitemaps.Sitemap``. They can live anywhere in your codebase.
  71. An example
  72. ==========
  73. Let's assume you have a blog system, with an ``Entry`` model, and you want your
  74. sitemap to include all the links to your individual blog entries. Here's how
  75. your sitemap class might look::
  76. from django.contrib.sitemaps import Sitemap
  77. from blog.models import Entry
  78. class BlogSitemap(Sitemap):
  79. changefreq = "never"
  80. priority = 0.5
  81. def items(self):
  82. return Entry.objects.filter(is_draft=False)
  83. def lastmod(self, obj):
  84. return obj.pub_date
  85. Note:
  86. * :attr:`~Sitemap.changefreq` and :attr:`~Sitemap.priority` are class
  87. attributes corresponding to ``<changefreq>`` and ``<priority>`` elements,
  88. respectively. They can be made callable as functions, as
  89. :attr:`~Sitemap.lastmod` was in the example.
  90. * :attr:`~Sitemap.items()` is a method that returns a :term:`sequence` or
  91. ``QuerySet`` of objects. The objects returned will get passed to any callable
  92. methods corresponding to a sitemap property (:attr:`~Sitemap.location`,
  93. :attr:`~Sitemap.lastmod`, :attr:`~Sitemap.changefreq`, and
  94. :attr:`~Sitemap.priority`).
  95. * :attr:`~Sitemap.lastmod` should return a :class:`~datetime.datetime`.
  96. * There is no :attr:`~Sitemap.location` method in this example, but you
  97. can provide it in order to specify the URL for your object. By default,
  98. :attr:`~Sitemap.location()` calls ``get_absolute_url()`` on each object
  99. and returns the result.
  100. ``Sitemap`` class reference
  101. ===========================
  102. .. class:: Sitemap
  103. A ``Sitemap`` class can define the following methods/attributes:
  104. .. attribute:: Sitemap.items
  105. **Required.** A method that returns a :term:`sequence` or ``QuerySet``
  106. of objects. The framework doesn't care what *type* of objects they are;
  107. all that matters is that these objects get passed to the
  108. :attr:`~Sitemap.location()`, :attr:`~Sitemap.lastmod()`,
  109. :attr:`~Sitemap.changefreq()` and :attr:`~Sitemap.priority()` methods.
  110. .. attribute:: Sitemap.location
  111. **Optional.** Either a method or attribute.
  112. If it's a method, it should return the absolute path for a given object
  113. as returned by :attr:`~Sitemap.items()`.
  114. If it's an attribute, its value should be a string representing an
  115. absolute path to use for *every* object returned by
  116. :attr:`~Sitemap.items()`.
  117. In both cases, "absolute path" means a URL that doesn't include the
  118. protocol or domain. Examples:
  119. * Good: ``'/foo/bar/'``
  120. * Bad: ``'example.com/foo/bar/'``
  121. * Bad: ``'https://example.com/foo/bar/'``
  122. If :attr:`~Sitemap.location` isn't provided, the framework will call
  123. the ``get_absolute_url()`` method on each object as returned by
  124. :attr:`~Sitemap.items()`.
  125. To specify a protocol other than ``'http'``, use
  126. :attr:`~Sitemap.protocol`.
  127. .. attribute:: Sitemap.lastmod
  128. **Optional.** Either a method or attribute.
  129. If it's a method, it should take one argument -- an object as returned
  130. by :attr:`~Sitemap.items()` -- and return that object's last-modified
  131. date/time as a :class:`~datetime.datetime`.
  132. If it's an attribute, its value should be a :class:`~datetime.datetime`
  133. representing the last-modified date/time for *every* object returned by
  134. :attr:`~Sitemap.items()`.
  135. If all items in a sitemap have a :attr:`~Sitemap.lastmod`, the sitemap
  136. generated by :func:`views.sitemap` will have a ``Last-Modified``
  137. header equal to the latest ``lastmod``. You can activate the
  138. :class:`~django.middleware.http.ConditionalGetMiddleware` to make
  139. Django respond appropriately to requests with an ``If-Modified-Since``
  140. header which will prevent sending the sitemap if it hasn't changed.
  141. .. attribute:: Sitemap.paginator
  142. **Optional.**
  143. This property returns a :class:`~django.core.paginator.Paginator` for
  144. :attr:`~Sitemap.items()`. If you generate sitemaps in a batch you may
  145. want to override this as a cached property in order to avoid multiple
  146. ``items()`` calls.
  147. .. attribute:: Sitemap.changefreq
  148. **Optional.** Either a method or attribute.
  149. If it's a method, it should take one argument -- an object as returned
  150. by :attr:`~Sitemap.items()` -- and return that object's change
  151. frequency as a string.
  152. If it's an attribute, its value should be a string representing the
  153. change frequency of *every* object returned by :attr:`~Sitemap.items()`.
  154. Possible values for :attr:`~Sitemap.changefreq`, whether you use a
  155. method or attribute, are:
  156. * ``'always'``
  157. * ``'hourly'``
  158. * ``'daily'``
  159. * ``'weekly'``
  160. * ``'monthly'``
  161. * ``'yearly'``
  162. * ``'never'``
  163. .. attribute:: Sitemap.priority
  164. **Optional.** Either a method or attribute.
  165. If it's a method, it should take one argument -- an object as returned
  166. by :attr:`~Sitemap.items()` -- and return that object's priority as
  167. either a string or float.
  168. If it's an attribute, its value should be either a string or float
  169. representing the priority of *every* object returned by
  170. :attr:`~Sitemap.items()`.
  171. Example values for :attr:`~Sitemap.priority`: ``0.4``, ``1.0``. The
  172. default priority of a page is ``0.5``. See the `sitemaps.org
  173. documentation`_ for more.
  174. .. _sitemaps.org documentation: https://www.sitemaps.org/protocol.html#prioritydef
  175. .. attribute:: Sitemap.protocol
  176. **Optional.**
  177. This attribute defines the protocol (``'http'`` or ``'https'``) of the
  178. URLs in the sitemap. If it isn't set, the protocol with which the
  179. sitemap was requested is used. If the sitemap is built outside the
  180. context of a request, the default is ``'https'``.
  181. .. versionchanged:: 5.0
  182. In older versions, the default protocol for sitemaps built outside
  183. the context of a request was ``'http'``.
  184. .. attribute:: Sitemap.limit
  185. **Optional.**
  186. This attribute defines the maximum number of URLs included on each page
  187. of the sitemap. Its value should not exceed the default value of
  188. ``50000``, which is the upper limit allowed in the `Sitemaps protocol
  189. <https://www.sitemaps.org/protocol.html#index>`_.
  190. .. attribute:: Sitemap.i18n
  191. **Optional.**
  192. A boolean attribute that defines if the URLs of this sitemap should
  193. be generated using all of your :setting:`LANGUAGES`. The default is
  194. ``False``.
  195. .. attribute:: Sitemap.languages
  196. **Optional.**
  197. A :term:`sequence` of :term:`language codes<language code>` to use for
  198. generating alternate links when :attr:`~Sitemap.i18n` is enabled.
  199. Defaults to :setting:`LANGUAGES`.
  200. .. attribute:: Sitemap.alternates
  201. **Optional.**
  202. A boolean attribute. When used in conjunction with
  203. :attr:`~Sitemap.i18n` generated URLs will each have a list of alternate
  204. links pointing to other language versions using the `hreflang
  205. attribute`_. The default is ``False``.
  206. .. _hreflang attribute: https://developers.google.com/search/docs/advanced/crawling/localized-versions
  207. .. attribute:: Sitemap.x_default
  208. **Optional.**
  209. A boolean attribute. When ``True`` the alternate links generated by
  210. :attr:`~Sitemap.alternates` will contain a ``hreflang="x-default"``
  211. fallback entry with a value of :setting:`LANGUAGE_CODE`. The default is
  212. ``False``.
  213. .. method:: Sitemap.get_latest_lastmod()
  214. **Optional.** A method that returns the latest value returned by
  215. :attr:`~Sitemap.lastmod`. This function is used to add the ``lastmod``
  216. attribute to :ref:`Sitemap index context
  217. variables<sitemap-index-context-variables>`.
  218. By default :meth:`~Sitemap.get_latest_lastmod` returns:
  219. * If :attr:`~Sitemap.lastmod` is an attribute:
  220. :attr:`~Sitemap.lastmod`.
  221. * If :attr:`~Sitemap.lastmod` is a method:
  222. The latest ``lastmod`` returned by calling the method with all
  223. items returned by :meth:`Sitemap.items`.
  224. .. method:: Sitemap.get_languages_for_item(item)
  225. .. versionadded:: 4.2
  226. **Optional.** A method that returns the sequence of language codes for
  227. which the item is displayed. By default
  228. :meth:`~Sitemap.get_languages_for_item` returns
  229. :attr:`~Sitemap.languages`.
  230. Shortcuts
  231. =========
  232. The sitemap framework provides a convenience class for a common case:
  233. .. class:: GenericSitemap(info_dict, priority=None, changefreq=None, protocol=None)
  234. The :class:`django.contrib.sitemaps.GenericSitemap` class allows you to
  235. create a sitemap by passing it a dictionary which has to contain at least
  236. a ``queryset`` entry. This queryset will be used to generate the items
  237. of the sitemap. It may also have a ``date_field`` entry that
  238. specifies a date field for objects retrieved from the ``queryset``.
  239. This will be used for the :attr:`~Sitemap.lastmod` attribute and
  240. :meth:`~Sitemap.get_latest_lastmod` methods in the in the
  241. generated sitemap.
  242. The :attr:`~Sitemap.priority`, :attr:`~Sitemap.changefreq`,
  243. and :attr:`~Sitemap.protocol` keyword arguments allow specifying these
  244. attributes for all URLs.
  245. Example
  246. -------
  247. Here's an example of a :doc:`URLconf </topics/http/urls>` using
  248. :class:`GenericSitemap`::
  249. from django.contrib.sitemaps import GenericSitemap
  250. from django.contrib.sitemaps.views import sitemap
  251. from django.urls import path
  252. from blog.models import Entry
  253. info_dict = {
  254. "queryset": Entry.objects.all(),
  255. "date_field": "pub_date",
  256. }
  257. urlpatterns = [
  258. # some generic view using info_dict
  259. # ...
  260. # the sitemap
  261. path(
  262. "sitemap.xml",
  263. sitemap,
  264. {"sitemaps": {"blog": GenericSitemap(info_dict, priority=0.6)}},
  265. name="django.contrib.sitemaps.views.sitemap",
  266. ),
  267. ]
  268. .. _URLconf: ../url_dispatch/
  269. Sitemap for static views
  270. ========================
  271. Often you want the search engine crawlers to index views which are neither
  272. object detail pages nor flatpages. The solution is to explicitly list URL
  273. names for these views in ``items`` and call :func:`~django.urls.reverse` in
  274. the ``location`` method of the sitemap. For example::
  275. # sitemaps.py
  276. from django.contrib import sitemaps
  277. from django.urls import reverse
  278. class StaticViewSitemap(sitemaps.Sitemap):
  279. priority = 0.5
  280. changefreq = "daily"
  281. def items(self):
  282. return ["main", "about", "license"]
  283. def location(self, item):
  284. return reverse(item)
  285. # urls.py
  286. from django.contrib.sitemaps.views import sitemap
  287. from django.urls import path
  288. from .sitemaps import StaticViewSitemap
  289. from . import views
  290. sitemaps = {
  291. "static": StaticViewSitemap,
  292. }
  293. urlpatterns = [
  294. path("", views.main, name="main"),
  295. path("about/", views.about, name="about"),
  296. path("license/", views.license, name="license"),
  297. # ...
  298. path(
  299. "sitemap.xml",
  300. sitemap,
  301. {"sitemaps": sitemaps},
  302. name="django.contrib.sitemaps.views.sitemap",
  303. ),
  304. ]
  305. Creating a sitemap index
  306. ========================
  307. .. function:: views.index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap')
  308. The sitemap framework also has the ability to create a sitemap index that
  309. references individual sitemap files, one per each section defined in your
  310. ``sitemaps`` dictionary. The only differences in usage are:
  311. * You use two views in your URLconf: :func:`django.contrib.sitemaps.views.index`
  312. and :func:`django.contrib.sitemaps.views.sitemap`.
  313. * The :func:`django.contrib.sitemaps.views.sitemap` view should take a
  314. ``section`` keyword argument.
  315. Here's what the relevant URLconf lines would look like for the example above::
  316. from django.contrib.sitemaps import views
  317. urlpatterns = [
  318. path(
  319. "sitemap.xml",
  320. views.index,
  321. {"sitemaps": sitemaps},
  322. name="django.contrib.sitemaps.views.index",
  323. ),
  324. path(
  325. "sitemap-<section>.xml",
  326. views.sitemap,
  327. {"sitemaps": sitemaps},
  328. name="django.contrib.sitemaps.views.sitemap",
  329. ),
  330. ]
  331. This will automatically generate a :file:`sitemap.xml` file that references
  332. both :file:`sitemap-flatpages.xml` and :file:`sitemap-blog.xml`. The
  333. :class:`~django.contrib.sitemaps.Sitemap` classes and the ``sitemaps``
  334. dict don't change at all.
  335. If all sitemaps have a ``lastmod`` returned by
  336. :meth:`Sitemap.get_latest_lastmod` the sitemap index will have a
  337. ``Last-Modified`` header equal to the latest ``lastmod``.
  338. You should create an index file if one of your sitemaps has more than 50,000
  339. URLs. In this case, Django will automatically paginate the sitemap, and the
  340. index will reflect that.
  341. If you're not using the vanilla sitemap view -- for example, if it's wrapped
  342. with a caching decorator -- you must name your sitemap view and pass
  343. ``sitemap_url_name`` to the index view::
  344. from django.contrib.sitemaps import views as sitemaps_views
  345. from django.views.decorators.cache import cache_page
  346. urlpatterns = [
  347. path(
  348. "sitemap.xml",
  349. cache_page(86400)(sitemaps_views.index),
  350. {"sitemaps": sitemaps, "sitemap_url_name": "sitemaps"},
  351. ),
  352. path(
  353. "sitemap-<section>.xml",
  354. cache_page(86400)(sitemaps_views.sitemap),
  355. {"sitemaps": sitemaps},
  356. name="sitemaps",
  357. ),
  358. ]
  359. Template customization
  360. ======================
  361. If you wish to use a different template for each sitemap or sitemap index
  362. available on your site, you may specify it by passing a ``template_name``
  363. parameter to the ``sitemap`` and ``index`` views via the URLconf::
  364. from django.contrib.sitemaps import views
  365. urlpatterns = [
  366. path(
  367. "custom-sitemap.xml",
  368. views.index,
  369. {"sitemaps": sitemaps, "template_name": "custom_sitemap.html"},
  370. name="django.contrib.sitemaps.views.index",
  371. ),
  372. path(
  373. "custom-sitemap-<section>.xml",
  374. views.sitemap,
  375. {"sitemaps": sitemaps, "template_name": "custom_sitemap.html"},
  376. name="django.contrib.sitemaps.views.sitemap",
  377. ),
  378. ]
  379. These views return :class:`~django.template.response.TemplateResponse`
  380. instances which allow you to easily customize the response data before
  381. rendering. For more details, see the :doc:`TemplateResponse documentation
  382. </ref/template-response>`.
  383. Context variables
  384. -----------------
  385. When customizing the templates for the
  386. :func:`~django.contrib.sitemaps.views.index` and
  387. :func:`~django.contrib.sitemaps.views.sitemap` views, you can rely on the
  388. following context variables.
  389. .. _sitemap-index-context-variables:
  390. Index
  391. -----
  392. The variable ``sitemaps`` is a list of objects containing the ``location`` and
  393. ``lastmod`` attribute for each of the sitemaps. Each URL exposes the following
  394. attributes:
  395. - ``location``: The location (url & page) of the sitemap.
  396. - ``lastmod``: Populated by the :meth:`~Sitemap.get_latest_lastmod`
  397. method for each sitemap.
  398. Sitemap
  399. -------
  400. The variable ``urlset`` is a list of URLs that should appear in the
  401. sitemap. Each URL exposes attributes as defined in the
  402. :class:`~django.contrib.sitemaps.Sitemap` class:
  403. - ``alternates``
  404. - ``changefreq``
  405. - ``item``
  406. - ``lastmod``
  407. - ``location``
  408. - ``priority``
  409. The ``alternates`` attribute is available when :attr:`~Sitemap.i18n` and
  410. :attr:`~Sitemap.alternates` are enabled. It is a list of other language
  411. versions, including the optional :attr:`~Sitemap.x_default` fallback, for each
  412. URL. Each alternate is a dictionary with ``location`` and ``lang_code`` keys.
  413. The ``item`` attribute has been added for each URL to allow more flexible
  414. customization of the templates, such as `Google news sitemaps`_. Assuming
  415. Sitemap's :attr:`~Sitemap.items()` would return a list of items with
  416. ``publication_data`` and a ``tags`` field something like this would
  417. generate a Google News compatible sitemap:
  418. .. code-block:: xml+django
  419. <?xml version="1.0" encoding="UTF-8"?>
  420. <urlset
  421. xmlns="https://www.sitemaps.org/schemas/sitemap/0.9"
  422. xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
  423. {% spaceless %}
  424. {% for url in urlset %}
  425. <url>
  426. <loc>{{ url.location }}</loc>
  427. {% if url.lastmod %}<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>{% endif %}
  428. {% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %}
  429. {% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %}
  430. <news:news>
  431. {% if url.item.publication_date %}<news:publication_date>{{ url.item.publication_date|date:"Y-m-d" }}</news:publication_date>{% endif %}
  432. {% if url.item.tags %}<news:keywords>{{ url.item.tags }}</news:keywords>{% endif %}
  433. </news:news>
  434. </url>
  435. {% endfor %}
  436. {% endspaceless %}
  437. </urlset>
  438. .. _`Google news sitemaps`: https://support.google.com/news/publisher-center/answer/9606710