2
0

sitemaps.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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. .. attribute:: Sitemap.limit
  182. **Optional.**
  183. This attribute defines the maximum number of URLs included on each page
  184. of the sitemap. Its value should not exceed the default value of
  185. ``50000``, which is the upper limit allowed in the `Sitemaps protocol
  186. <https://www.sitemaps.org/protocol.html#index>`_.
  187. .. attribute:: Sitemap.i18n
  188. **Optional.**
  189. A boolean attribute that defines if the URLs of this sitemap should
  190. be generated using all of your :setting:`LANGUAGES`. The default is
  191. ``False``.
  192. .. attribute:: Sitemap.languages
  193. **Optional.**
  194. A :term:`sequence` of :term:`language codes<language code>` to use for
  195. generating alternate links when :attr:`~Sitemap.i18n` is enabled.
  196. Defaults to :setting:`LANGUAGES`.
  197. .. attribute:: Sitemap.alternates
  198. **Optional.**
  199. A boolean attribute. When used in conjunction with
  200. :attr:`~Sitemap.i18n` generated URLs will each have a list of alternate
  201. links pointing to other language versions using the `hreflang
  202. attribute`_. The default is ``False``.
  203. .. _hreflang attribute: https://developers.google.com/search/docs/advanced/crawling/localized-versions
  204. .. attribute:: Sitemap.x_default
  205. **Optional.**
  206. A boolean attribute. When ``True`` the alternate links generated by
  207. :attr:`~Sitemap.alternates` will contain a ``hreflang="x-default"``
  208. fallback entry with a value of :setting:`LANGUAGE_CODE`. The default is
  209. ``False``.
  210. .. method:: Sitemap.get_latest_lastmod()
  211. **Optional.** A method that returns the latest value returned by
  212. :attr:`~Sitemap.lastmod`. This function is used to add the ``lastmod``
  213. attribute to :ref:`Sitemap index context
  214. variables<sitemap-index-context-variables>`.
  215. By default :meth:`~Sitemap.get_latest_lastmod` returns:
  216. * If :attr:`~Sitemap.lastmod` is an attribute:
  217. :attr:`~Sitemap.lastmod`.
  218. * If :attr:`~Sitemap.lastmod` is a method:
  219. The latest ``lastmod`` returned by calling the method with all
  220. items returned by :meth:`Sitemap.items`.
  221. .. method:: Sitemap.get_languages_for_item(item)
  222. **Optional.** A method that returns the sequence of language codes for
  223. which the item is displayed. By default
  224. :meth:`~Sitemap.get_languages_for_item` returns
  225. :attr:`~Sitemap.languages`.
  226. Shortcuts
  227. =========
  228. The sitemap framework provides a convenience class for a common case:
  229. .. class:: GenericSitemap(info_dict, priority=None, changefreq=None, protocol=None)
  230. The :class:`django.contrib.sitemaps.GenericSitemap` class allows you to
  231. create a sitemap by passing it a dictionary which has to contain at least
  232. a ``queryset`` entry. This queryset will be used to generate the items
  233. of the sitemap. It may also have a ``date_field`` entry that
  234. specifies a date field for objects retrieved from the ``queryset``.
  235. This will be used for the :attr:`~Sitemap.lastmod` attribute and
  236. :meth:`~Sitemap.get_latest_lastmod` methods in the in the
  237. generated sitemap.
  238. The :attr:`~Sitemap.priority`, :attr:`~Sitemap.changefreq`,
  239. and :attr:`~Sitemap.protocol` keyword arguments allow specifying these
  240. attributes for all URLs.
  241. Example
  242. -------
  243. Here's an example of a :doc:`URLconf </topics/http/urls>` using
  244. :class:`GenericSitemap`::
  245. from django.contrib.sitemaps import GenericSitemap
  246. from django.contrib.sitemaps.views import sitemap
  247. from django.urls import path
  248. from blog.models import Entry
  249. info_dict = {
  250. "queryset": Entry.objects.all(),
  251. "date_field": "pub_date",
  252. }
  253. urlpatterns = [
  254. # some generic view using info_dict
  255. # ...
  256. # the sitemap
  257. path(
  258. "sitemap.xml",
  259. sitemap,
  260. {"sitemaps": {"blog": GenericSitemap(info_dict, priority=0.6)}},
  261. name="django.contrib.sitemaps.views.sitemap",
  262. ),
  263. ]
  264. .. _URLconf: ../url_dispatch/
  265. Sitemap for static views
  266. ========================
  267. Often you want the search engine crawlers to index views which are neither
  268. object detail pages nor flatpages. The solution is to explicitly list URL
  269. names for these views in ``items`` and call :func:`~django.urls.reverse` in
  270. the ``location`` method of the sitemap. For example::
  271. # sitemaps.py
  272. from django.contrib import sitemaps
  273. from django.urls import reverse
  274. class StaticViewSitemap(sitemaps.Sitemap):
  275. priority = 0.5
  276. changefreq = "daily"
  277. def items(self):
  278. return ["main", "about", "license"]
  279. def location(self, item):
  280. return reverse(item)
  281. # urls.py
  282. from django.contrib.sitemaps.views import sitemap
  283. from django.urls import path
  284. from .sitemaps import StaticViewSitemap
  285. from . import views
  286. sitemaps = {
  287. "static": StaticViewSitemap,
  288. }
  289. urlpatterns = [
  290. path("", views.main, name="main"),
  291. path("about/", views.about, name="about"),
  292. path("license/", views.license, name="license"),
  293. # ...
  294. path(
  295. "sitemap.xml",
  296. sitemap,
  297. {"sitemaps": sitemaps},
  298. name="django.contrib.sitemaps.views.sitemap",
  299. ),
  300. ]
  301. Creating a sitemap index
  302. ========================
  303. .. function:: views.index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap')
  304. The sitemap framework also has the ability to create a sitemap index that
  305. references individual sitemap files, one per each section defined in your
  306. ``sitemaps`` dictionary. The only differences in usage are:
  307. * You use two views in your URLconf: :func:`django.contrib.sitemaps.views.index`
  308. and :func:`django.contrib.sitemaps.views.sitemap`.
  309. * The :func:`django.contrib.sitemaps.views.sitemap` view should take a
  310. ``section`` keyword argument.
  311. Here's what the relevant URLconf lines would look like for the example above::
  312. from django.contrib.sitemaps import views
  313. urlpatterns = [
  314. path(
  315. "sitemap.xml",
  316. views.index,
  317. {"sitemaps": sitemaps},
  318. name="django.contrib.sitemaps.views.index",
  319. ),
  320. path(
  321. "sitemap-<section>.xml",
  322. views.sitemap,
  323. {"sitemaps": sitemaps},
  324. name="django.contrib.sitemaps.views.sitemap",
  325. ),
  326. ]
  327. This will automatically generate a :file:`sitemap.xml` file that references
  328. both :file:`sitemap-flatpages.xml` and :file:`sitemap-blog.xml`. The
  329. :class:`~django.contrib.sitemaps.Sitemap` classes and the ``sitemaps``
  330. dict don't change at all.
  331. If all sitemaps have a ``lastmod`` returned by
  332. :meth:`Sitemap.get_latest_lastmod` the sitemap index will have a
  333. ``Last-Modified`` header equal to the latest ``lastmod``.
  334. You should create an index file if one of your sitemaps has more than 50,000
  335. URLs. In this case, Django will automatically paginate the sitemap, and the
  336. index will reflect that.
  337. If you're not using the vanilla sitemap view -- for example, if it's wrapped
  338. with a caching decorator -- you must name your sitemap view and pass
  339. ``sitemap_url_name`` to the index view::
  340. from django.contrib.sitemaps import views as sitemaps_views
  341. from django.views.decorators.cache import cache_page
  342. urlpatterns = [
  343. path(
  344. "sitemap.xml",
  345. cache_page(86400)(sitemaps_views.index),
  346. {"sitemaps": sitemaps, "sitemap_url_name": "sitemaps"},
  347. ),
  348. path(
  349. "sitemap-<section>.xml",
  350. cache_page(86400)(sitemaps_views.sitemap),
  351. {"sitemaps": sitemaps},
  352. name="sitemaps",
  353. ),
  354. ]
  355. Template customization
  356. ======================
  357. If you wish to use a different template for each sitemap or sitemap index
  358. available on your site, you may specify it by passing a ``template_name``
  359. parameter to the ``sitemap`` and ``index`` views via the URLconf::
  360. from django.contrib.sitemaps import views
  361. urlpatterns = [
  362. path(
  363. "custom-sitemap.xml",
  364. views.index,
  365. {"sitemaps": sitemaps, "template_name": "custom_sitemap.html"},
  366. name="django.contrib.sitemaps.views.index",
  367. ),
  368. path(
  369. "custom-sitemap-<section>.xml",
  370. views.sitemap,
  371. {"sitemaps": sitemaps, "template_name": "custom_sitemap.html"},
  372. name="django.contrib.sitemaps.views.sitemap",
  373. ),
  374. ]
  375. These views return :class:`~django.template.response.TemplateResponse`
  376. instances which allow you to easily customize the response data before
  377. rendering. For more details, see the :doc:`TemplateResponse documentation
  378. </ref/template-response>`.
  379. Context variables
  380. -----------------
  381. When customizing the templates for the
  382. :func:`~django.contrib.sitemaps.views.index` and
  383. :func:`~django.contrib.sitemaps.views.sitemap` views, you can rely on the
  384. following context variables.
  385. .. _sitemap-index-context-variables:
  386. Index
  387. -----
  388. The variable ``sitemaps`` is a list of objects containing the ``location`` and
  389. ``lastmod`` attribute for each of the sitemaps. Each URL exposes the following
  390. attributes:
  391. - ``location``: The location (url & page) of the sitemap.
  392. - ``lastmod``: Populated by the :meth:`~Sitemap.get_latest_lastmod`
  393. method for each sitemap.
  394. Sitemap
  395. -------
  396. The variable ``urlset`` is a list of URLs that should appear in the
  397. sitemap. Each URL exposes attributes as defined in the
  398. :class:`~django.contrib.sitemaps.Sitemap` class:
  399. - ``alternates``
  400. - ``changefreq``
  401. - ``item``
  402. - ``lastmod``
  403. - ``location``
  404. - ``priority``
  405. The ``alternates`` attribute is available when :attr:`~Sitemap.i18n` and
  406. :attr:`~Sitemap.alternates` are enabled. It is a list of other language
  407. versions, including the optional :attr:`~Sitemap.x_default` fallback, for each
  408. URL. Each alternate is a dictionary with ``location`` and ``lang_code`` keys.
  409. The ``item`` attribute has been added for each URL to allow more flexible
  410. customization of the templates, such as `Google news sitemaps`_. Assuming
  411. Sitemap's :attr:`~Sitemap.items()` would return a list of items with
  412. ``publication_data`` and a ``tags`` field something like this would
  413. generate a Google News compatible sitemap:
  414. .. code-block:: xml+django
  415. <?xml version="1.0" encoding="UTF-8"?>
  416. <urlset
  417. xmlns="https://www.sitemaps.org/schemas/sitemap/0.9"
  418. xmlns:news="https://www.google.com/schemas/sitemap-news/0.9">
  419. {% spaceless %}
  420. {% for url in urlset %}
  421. <url>
  422. <loc>{{ url.location }}</loc>
  423. {% if url.lastmod %}<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>{% endif %}
  424. {% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %}
  425. {% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %}
  426. <news:news>
  427. {% if url.item.publication_date %}<news:publication_date>{{ url.item.publication_date|date:"Y-m-d" }}</news:publication_date>{% endif %}
  428. {% if url.item.tags %}<news:keywords>{{ url.item.tags }}</news:keywords>{% endif %}
  429. </news:news>
  430. </url>
  431. {% endfor %}
  432. {% endspaceless %}
  433. </urlset>
  434. .. _`Google news sitemaps`: https://support.google.com/news/publisher-center/answer/9606710