sitemaps.txt 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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('sitemap.xml', sitemap, {'sitemaps': sitemaps},
  40. name='django.contrib.sitemaps.views.sitemap')
  41. This tells Django to build a sitemap when a client accesses :file:`/sitemap.xml`.
  42. The name of the sitemap file is not important, but the location is. Search
  43. engines will only index links in your sitemap for the current URL level and
  44. below. For instance, if :file:`sitemap.xml` lives in your root directory, it may
  45. reference any URL in your site. However, if your sitemap lives at
  46. :file:`/content/sitemap.xml`, it may only reference URLs that begin with
  47. :file:`/content/`.
  48. The sitemap view takes an extra, required argument: ``{'sitemaps': sitemaps}``.
  49. ``sitemaps`` should be a dictionary that maps a short section label (e.g.,
  50. ``blog`` or ``news``) to its :class:`~django.contrib.sitemaps.Sitemap` class
  51. (e.g., ``BlogSitemap`` or ``NewsSitemap``). It may also map to an *instance* of
  52. a :class:`~django.contrib.sitemaps.Sitemap` class (e.g.,
  53. ``BlogSitemap(some_var)``).
  54. ``Sitemap`` classes
  55. ===================
  56. A :class:`~django.contrib.sitemaps.Sitemap` class is a Python class that
  57. represents a "section" of entries in your sitemap. For example, one
  58. :class:`~django.contrib.sitemaps.Sitemap` class could represent all the entries
  59. of your Weblog, while another could represent all of the events in your events
  60. calendar.
  61. In the simplest case, all these sections get lumped together into one
  62. :file:`sitemap.xml`, but it's also possible to use the framework to generate a
  63. sitemap index that references individual sitemap files, one per section. (See
  64. `Creating a sitemap index`_ below.)
  65. :class:`~django.contrib.sitemaps.Sitemap` classes must subclass
  66. ``django.contrib.sitemaps.Sitemap``. They can live anywhere in your codebase.
  67. An example
  68. ==========
  69. Let's assume you have a blog system, with an ``Entry`` model, and you want your
  70. sitemap to include all the links to your individual blog entries. Here's how
  71. your sitemap class might look::
  72. from django.contrib.sitemaps import Sitemap
  73. from blog.models import Entry
  74. class BlogSitemap(Sitemap):
  75. changefreq = "never"
  76. priority = 0.5
  77. def items(self):
  78. return Entry.objects.filter(is_draft=False)
  79. def lastmod(self, obj):
  80. return obj.pub_date
  81. Note:
  82. * :attr:`~Sitemap.changefreq` and :attr:`~Sitemap.priority` are class
  83. attributes corresponding to ``<changefreq>`` and ``<priority>`` elements,
  84. respectively. They can be made callable as functions, as
  85. :attr:`~Sitemap.lastmod` was in the example.
  86. * :attr:`~Sitemap.items()` is a method that returns a list of objects. The
  87. objects returned will get passed to any callable methods corresponding to a
  88. sitemap property (:attr:`~Sitemap.location`, :attr:`~Sitemap.lastmod`,
  89. :attr:`~Sitemap.changefreq`, and :attr:`~Sitemap.priority`).
  90. * :attr:`~Sitemap.lastmod` should return a :class:`~datetime.datetime`.
  91. * There is no :attr:`~Sitemap.location` method in this example, but you
  92. can provide it in order to specify the URL for your object. By default,
  93. :attr:`~Sitemap.location()` calls ``get_absolute_url()`` on each object
  94. and returns the result.
  95. ``Sitemap`` class reference
  96. ===========================
  97. .. class:: Sitemap
  98. A ``Sitemap`` class can define the following methods/attributes:
  99. .. attribute:: Sitemap.items
  100. **Required.** A method that returns a list of objects. The framework
  101. doesn't care what *type* of objects they are; all that matters is that
  102. these objects get passed to the :attr:`~Sitemap.location()`,
  103. :attr:`~Sitemap.lastmod()`, :attr:`~Sitemap.changefreq()` and
  104. :attr:`~Sitemap.priority()` methods.
  105. .. attribute:: Sitemap.location
  106. **Optional.** Either a method or attribute.
  107. If it's a method, it should return the absolute path for a given object
  108. as returned by :attr:`~Sitemap.items()`.
  109. If it's an attribute, its value should be a string representing an
  110. absolute path to use for *every* object returned by
  111. :attr:`~Sitemap.items()`.
  112. In both cases, "absolute path" means a URL that doesn't include the
  113. protocol or domain. Examples:
  114. * Good: :file:`'/foo/bar/'`
  115. * Bad: :file:`'example.com/foo/bar/'`
  116. * Bad: :file:`'https://example.com/foo/bar/'`
  117. If :attr:`~Sitemap.location` isn't provided, the framework will call
  118. the ``get_absolute_url()`` method on each object as returned by
  119. :attr:`~Sitemap.items()`.
  120. To specify a protocol other than ``'http'``, use
  121. :attr:`~Sitemap.protocol`.
  122. .. attribute:: Sitemap.lastmod
  123. **Optional.** Either a method or attribute.
  124. If it's a method, it should take one argument -- an object as returned
  125. by :attr:`~Sitemap.items()` -- and return that object's last-modified
  126. date/time as a :class:`~datetime.datetime`.
  127. If it's an attribute, its value should be a :class:`~datetime.datetime`
  128. representing the last-modified date/time for *every* object returned by
  129. :attr:`~Sitemap.items()`.
  130. If all items in a sitemap have a :attr:`~Sitemap.lastmod`, the sitemap
  131. generated by :func:`views.sitemap` will have a ``Last-Modified``
  132. header equal to the latest ``lastmod``. You can activate the
  133. :class:`~django.middleware.http.ConditionalGetMiddleware` to make
  134. Django respond appropriately to requests with an ``If-Modified-Since``
  135. header which will prevent sending the sitemap if it hasn't changed.
  136. .. attribute:: Sitemap.changefreq
  137. **Optional.** Either a method or attribute.
  138. If it's a method, it should take one argument -- an object as returned
  139. by :attr:`~Sitemap.items()` -- and return that object's change
  140. frequency as a string.
  141. If it's an attribute, its value should be a string representing the
  142. change frequency of *every* object returned by :attr:`~Sitemap.items()`.
  143. Possible values for :attr:`~Sitemap.changefreq`, whether you use a
  144. method or attribute, are:
  145. * ``'always'``
  146. * ``'hourly'``
  147. * ``'daily'``
  148. * ``'weekly'``
  149. * ``'monthly'``
  150. * ``'yearly'``
  151. * ``'never'``
  152. .. attribute:: Sitemap.priority
  153. **Optional.** Either a method or attribute.
  154. If it's a method, it should take one argument -- an object as returned
  155. by :attr:`~Sitemap.items()` -- and return that object's priority as
  156. either a string or float.
  157. If it's an attribute, its value should be either a string or float
  158. representing the priority of *every* object returned by
  159. :attr:`~Sitemap.items()`.
  160. Example values for :attr:`~Sitemap.priority`: ``0.4``, ``1.0``. The
  161. default priority of a page is ``0.5``. See the `sitemaps.org
  162. documentation`_ for more.
  163. .. _sitemaps.org documentation: https://www.sitemaps.org/protocol.html#prioritydef
  164. .. attribute:: Sitemap.protocol
  165. **Optional.**
  166. This attribute defines the protocol (``'http'`` or ``'https'``) of the
  167. URLs in the sitemap. If it isn't set, the protocol with which the
  168. sitemap was requested is used. If the sitemap is built outside the
  169. context of a request, the default is ``'http'``.
  170. .. attribute:: Sitemap.limit
  171. **Optional.**
  172. This attribute defines the maximum number of URLs included on each page
  173. of the sitemap. Its value should not exceed the default value of
  174. ``50000``, which is the upper limit allowed in the `Sitemaps protocol
  175. <https://www.sitemaps.org/protocol.html#index>`_.
  176. .. attribute:: Sitemap.i18n
  177. **Optional.**
  178. A boolean attribute that defines if the URLs of this sitemap should
  179. be generated using all of your :setting:`LANGUAGES`. The default is
  180. ``False``.
  181. Shortcuts
  182. =========
  183. The sitemap framework provides a convenience class for a common case:
  184. .. class:: GenericSitemap(info_dict, priority=None, changefreq=None, protocol=None)
  185. The :class:`django.contrib.sitemaps.GenericSitemap` class allows you to
  186. create a sitemap by passing it a dictionary which has to contain at least
  187. a ``queryset`` entry. This queryset will be used to generate the items
  188. of the sitemap. It may also have a ``date_field`` entry that
  189. specifies a date field for objects retrieved from the ``queryset``.
  190. This will be used for the :attr:`~Sitemap.lastmod` attribute in the
  191. generated sitemap.
  192. The :attr:`~Sitemap.priority`, :attr:`~Sitemap.changefreq`,
  193. and :attr:`~Sitemap.protocol` keyword arguments allow specifying these
  194. attributes for all URLs.
  195. Example
  196. -------
  197. Here's an example of a :doc:`URLconf </topics/http/urls>` using
  198. :class:`GenericSitemap`::
  199. from django.contrib.sitemaps import GenericSitemap
  200. from django.contrib.sitemaps.views import sitemap
  201. from django.urls import path
  202. from blog.models import Entry
  203. info_dict = {
  204. 'queryset': Entry.objects.all(),
  205. 'date_field': 'pub_date',
  206. }
  207. urlpatterns = [
  208. # some generic view using info_dict
  209. # ...
  210. # the sitemap
  211. path('sitemap.xml', sitemap,
  212. {'sitemaps': {'blog': GenericSitemap(info_dict, priority=0.6)}},
  213. name='django.contrib.sitemaps.views.sitemap'),
  214. ]
  215. .. _URLconf: ../url_dispatch/
  216. Sitemap for static views
  217. ========================
  218. Often you want the search engine crawlers to index views which are neither
  219. object detail pages nor flatpages. The solution is to explicitly list URL
  220. names for these views in ``items`` and call :func:`~django.urls.reverse` in
  221. the ``location`` method of the sitemap. For example::
  222. # sitemaps.py
  223. from django.contrib import sitemaps
  224. from django.urls import reverse
  225. class StaticViewSitemap(sitemaps.Sitemap):
  226. priority = 0.5
  227. changefreq = 'daily'
  228. def items(self):
  229. return ['main', 'about', 'license']
  230. def location(self, item):
  231. return reverse(item)
  232. # urls.py
  233. from django.contrib.sitemaps.views import sitemap
  234. from django.urls import path
  235. from .sitemaps import StaticViewSitemap
  236. from . import views
  237. sitemaps = {
  238. 'static': StaticViewSitemap,
  239. }
  240. urlpatterns = [
  241. path('', views.main, name='main'),
  242. path('about/', views.about, name='about'),
  243. path('license/', views.license, name='license'),
  244. # ...
  245. path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
  246. name='django.contrib.sitemaps.views.sitemap')
  247. ]
  248. Creating a sitemap index
  249. ========================
  250. .. function:: views.index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap')
  251. The sitemap framework also has the ability to create a sitemap index that
  252. references individual sitemap files, one per each section defined in your
  253. ``sitemaps`` dictionary. The only differences in usage are:
  254. * You use two views in your URLconf: :func:`django.contrib.sitemaps.views.index`
  255. and :func:`django.contrib.sitemaps.views.sitemap`.
  256. * The :func:`django.contrib.sitemaps.views.sitemap` view should take a
  257. ``section`` keyword argument.
  258. Here's what the relevant URLconf lines would look like for the example above::
  259. from django.contrib.sitemaps import views
  260. urlpatterns = [
  261. path('sitemap.xml', views.index, {'sitemaps': sitemaps}),
  262. path('sitemap-<section>.xml', views.sitemap, {'sitemaps': sitemaps},
  263. name='django.contrib.sitemaps.views.sitemap'),
  264. ]
  265. This will automatically generate a :file:`sitemap.xml` file that references
  266. both :file:`sitemap-flatpages.xml` and :file:`sitemap-blog.xml`. The
  267. :class:`~django.contrib.sitemaps.Sitemap` classes and the ``sitemaps``
  268. dict don't change at all.
  269. You should create an index file if one of your sitemaps has more than 50,000
  270. URLs. In this case, Django will automatically paginate the sitemap, and the
  271. index will reflect that.
  272. If you're not using the vanilla sitemap view -- for example, if it's wrapped
  273. with a caching decorator -- you must name your sitemap view and pass
  274. ``sitemap_url_name`` to the index view::
  275. from django.contrib.sitemaps import views as sitemaps_views
  276. from django.views.decorators.cache import cache_page
  277. urlpatterns = [
  278. path('sitemap.xml',
  279. cache_page(86400)(sitemaps_views.index),
  280. {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),
  281. path('sitemap-<section>.xml',
  282. cache_page(86400)(sitemaps_views.sitemap),
  283. {'sitemaps': sitemaps}, name='sitemaps'),
  284. ]
  285. Template customization
  286. ======================
  287. If you wish to use a different template for each sitemap or sitemap index
  288. available on your site, you may specify it by passing a ``template_name``
  289. parameter to the ``sitemap`` and ``index`` views via the URLconf::
  290. from django.contrib.sitemaps import views
  291. urlpatterns = [
  292. path('custom-sitemap.xml', views.index, {
  293. 'sitemaps': sitemaps,
  294. 'template_name': 'custom_sitemap.html'
  295. }),
  296. path('custom-sitemap-<section>.xml', views.sitemap, {
  297. 'sitemaps': sitemaps,
  298. 'template_name': 'custom_sitemap.html'
  299. }, name='django.contrib.sitemaps.views.sitemap'),
  300. ]
  301. These views return :class:`~django.template.response.TemplateResponse`
  302. instances which allow you to easily customize the response data before
  303. rendering. For more details, see the :doc:`TemplateResponse documentation
  304. </ref/template-response>`.
  305. Context variables
  306. -----------------
  307. When customizing the templates for the
  308. :func:`~django.contrib.sitemaps.views.index` and
  309. :func:`~django.contrib.sitemaps.views.sitemap` views, you can rely on the
  310. following context variables.
  311. Index
  312. -----
  313. The variable ``sitemaps`` is a list of absolute URLs to each of the sitemaps.
  314. Sitemap
  315. -------
  316. The variable ``urlset`` is a list of URLs that should appear in the
  317. sitemap. Each URL exposes attributes as defined in the
  318. :class:`~django.contrib.sitemaps.Sitemap` class:
  319. - ``changefreq``
  320. - ``item``
  321. - ``lastmod``
  322. - ``location``
  323. - ``priority``
  324. The ``item`` attribute has been added for each URL to allow more flexible
  325. customization of the templates, such as `Google news sitemaps`_. Assuming
  326. Sitemap's :attr:`~Sitemap.items()` would return a list of items with
  327. ``publication_data`` and a ``tags`` field something like this would
  328. generate a Google News compatible sitemap:
  329. .. code-block:: xml+django
  330. <?xml version="1.0" encoding="UTF-8"?>
  331. <urlset
  332. xmlns="https://www.sitemaps.org/schemas/sitemap/0.9"
  333. xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
  334. {% spaceless %}
  335. {% for url in urlset %}
  336. <url>
  337. <loc>{{ url.location }}</loc>
  338. {% if url.lastmod %}<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>{% endif %}
  339. {% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %}
  340. {% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %}
  341. <news:news>
  342. {% if url.item.publication_date %}<news:publication_date>{{ url.item.publication_date|date:"Y-m-d" }}</news:publication_date>{% endif %}
  343. {% if url.item.tags %}<news:keywords>{{ url.item.tags }}</news:keywords>{% endif %}
  344. </news:news>
  345. </url>
  346. {% endfor %}
  347. {% endspaceless %}
  348. </urlset>
  349. .. _`Google news sitemaps`: https://support.google.com/news/publisher/answer/74288?hl=en
  350. Pinging Google
  351. ==============
  352. You may want to "ping" Google when your sitemap changes, to let it know to
  353. reindex your site. The sitemaps framework provides a function to do just
  354. that: :func:`django.contrib.sitemaps.ping_google()`.
  355. .. function:: ping_google(sitemap_url=None, ping_url=PING_URL, sitemap_uses_https=True)
  356. ``ping_google`` takes these optional arguments:
  357. * ``sitemap_url`` - The absolute path to your site's sitemap (e.g.,
  358. :file:`'/sitemap.xml'`). If this argument isn't provided, ``ping_google``
  359. will attempt to figure out your sitemap by performing a reverse lookup in
  360. your URLconf.
  361. * ``ping_url`` - Defaults to Google's Ping Tool:
  362. https://www.google.com/webmasters/tools/ping.
  363. * ``sitemap_uses_https`` - Set to ``False`` if your site uses ``http``
  364. rather than ``https``.
  365. :func:`ping_google` raises the exception
  366. ``django.contrib.sitemaps.SitemapNotFound`` if it cannot determine your
  367. sitemap URL.
  368. .. versionadded:: 2.2
  369. The ``sitemap_uses_https`` argument was added. Older versions of
  370. Django always use ``http`` for a sitemap's URL.
  371. .. admonition:: Register with Google first!
  372. The :func:`ping_google` command only works if you have registered your
  373. site with `Google Webmaster Tools`_.
  374. .. _`Google Webmaster Tools`: https://www.google.com/webmasters/tools/
  375. One useful way to call :func:`ping_google` is from a model's ``save()``
  376. method::
  377. from django.contrib.sitemaps import ping_google
  378. class Entry(models.Model):
  379. # ...
  380. def save(self, force_insert=False, force_update=False):
  381. super().save(force_insert, force_update)
  382. try:
  383. ping_google()
  384. except Exception:
  385. # Bare 'except' because we could get a variety
  386. # of HTTP-related exceptions.
  387. pass
  388. A more efficient solution, however, would be to call :func:`ping_google` from a
  389. cron script, or some other scheduled task. The function makes an HTTP request
  390. to Google's servers, so you may not want to introduce that network overhead
  391. each time you call ``save()``.
  392. Pinging Google via ``manage.py``
  393. --------------------------------
  394. .. django-admin:: ping_google [sitemap_url]
  395. Once the sitemaps application is added to your project, you may also
  396. ping Google using the ``ping_google`` management command::
  397. python manage.py ping_google [/sitemap.xml]
  398. .. django-admin-option:: --sitemap-uses-http
  399. .. versionadded:: 2.2
  400. Use this option if your sitemap uses ``http`` rather than ``https``.