=====================The sitemap framework=====================.. module:: django.contrib.sitemaps:synopsis: A framework for generating Google sitemap XML files.Django comes with a high-level sitemap-generating framework to create sitemap_XML files... _sitemap: https://www.sitemaps.org/Overview========A sitemap is an XML file on your website that tells search-engine indexers howfrequently your pages change and how "important" certain pages are in relationto other pages on your site. This information helps search engines index yoursite.The Django sitemap framework automates the creation of this XML file by lettingyou express this information in Python code.It works much like Django's :doc:`syndication framework</ref/contrib/syndication>`. To create a sitemap, write a:class:`~django.contrib.sitemaps.Sitemap` class and point to it in your:doc:`URLconf </topics/http/urls>`.Installation============To install the sitemap app, follow these steps:#. Add ``'django.contrib.sitemaps'`` to your :setting:`INSTALLED_APPS` setting.#. Make sure your :setting:`TEMPLATES` setting contains a ``DjangoTemplates``backend whose ``APP_DIRS`` options is set to ``True``. It's in there bydefault, so you'll only need to change this if you've changed that setting.#. Make sure you've installed the :mod:`sites framework<django.contrib.sites>`.(Note: The sitemap application doesn't install any database tables. The onlyreason it needs to go into :setting:`INSTALLED_APPS` is so that the:func:`~django.template.loaders.app_directories.Loader` templateloader can find the default templates.)Initialization==============.. function:: views.sitemap(request, sitemaps, section=None, template_name='sitemap.xml', content_type='application/xml')To activate sitemap generation on your Django site, add this line to your:doc:`URLconf </topics/http/urls>`::from django.contrib.sitemaps.views import sitemappath('sitemap.xml', sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap')This tells Django to build a sitemap when a client accesses :file:`/sitemap.xml`.The name of the sitemap file is not important, but the location is. Searchengines will only index links in your sitemap for the current URL level andbelow. For instance, if :file:`sitemap.xml` lives in your root directory, it mayreference any URL in your site. However, if your sitemap lives at:file:`/content/sitemap.xml`, it may only reference URLs that begin with:file:`/content/`.The sitemap view takes an extra, required argument: ``{'sitemaps': sitemaps}``.``sitemaps`` should be a dictionary that maps a short section label (e.g.,``blog`` or ``news``) to its :class:`~django.contrib.sitemaps.Sitemap` class(e.g., ``BlogSitemap`` or ``NewsSitemap``). It may also map to an *instance* ofa :class:`~django.contrib.sitemaps.Sitemap` class (e.g.,``BlogSitemap(some_var)``).``Sitemap`` classes===================A :class:`~django.contrib.sitemaps.Sitemap` class is a Python class thatrepresents a "section" of entries in your sitemap. For example, one:class:`~django.contrib.sitemaps.Sitemap` class could represent all the entriesof your blog, while another could represent all of the events in your eventscalendar.In the simplest case, all these sections get lumped together into one:file:`sitemap.xml`, but it's also possible to use the framework to generate asitemap index that references individual sitemap files, one per section. (See`Creating a sitemap index`_ below.):class:`~django.contrib.sitemaps.Sitemap` classes must subclass``django.contrib.sitemaps.Sitemap``. They can live anywhere in your codebase.An example==========Let's assume you have a blog system, with an ``Entry`` model, and you want yoursitemap to include all the links to your individual blog entries. Here's howyour sitemap class might look::from django.contrib.sitemaps import Sitemapfrom blog.models import Entryclass BlogSitemap(Sitemap):changefreq = "never"priority = 0.5def items(self):return Entry.objects.filter(is_draft=False)def lastmod(self, obj):return obj.pub_dateNote:* :attr:`~Sitemap.changefreq` and :attr:`~Sitemap.priority` are classattributes corresponding to ``<changefreq>`` and ``<priority>`` elements,respectively. They can be made callable as functions, as:attr:`~Sitemap.lastmod` was in the example.* :attr:`~Sitemap.items()` is a method that returns a :term:`sequence` or``QuerySet`` of objects. The objects returned will get passed to any callablemethods corresponding to a sitemap property (:attr:`~Sitemap.location`,:attr:`~Sitemap.lastmod`, :attr:`~Sitemap.changefreq`, and:attr:`~Sitemap.priority`).* :attr:`~Sitemap.lastmod` should return a :class:`~datetime.datetime`.* There is no :attr:`~Sitemap.location` method in this example, but youcan provide it in order to specify the URL for your object. By default,:attr:`~Sitemap.location()` calls ``get_absolute_url()`` on each objectand returns the result.``Sitemap`` class reference===========================.. class:: SitemapA ``Sitemap`` class can define the following methods/attributes:.. attribute:: Sitemap.items**Required.** A method that returns a :term:`sequence` or ``QuerySet``of objects. The framework doesn't care what *type* of objects they are;all that matters is that these objects get passed to the:attr:`~Sitemap.location()`, :attr:`~Sitemap.lastmod()`,:attr:`~Sitemap.changefreq()` and :attr:`~Sitemap.priority()` methods... attribute:: Sitemap.location**Optional.** Either a method or attribute.If it's a method, it should return the absolute path for a given objectas returned by :attr:`~Sitemap.items()`.If it's an attribute, its value should be a string representing anabsolute path to use for *every* object returned by:attr:`~Sitemap.items()`.In both cases, "absolute path" means a URL that doesn't include theprotocol or domain. Examples:* Good: :file:`'/foo/bar/'`* Bad: :file:`'example.com/foo/bar/'`* Bad: :file:`'https://example.com/foo/bar/'`If :attr:`~Sitemap.location` isn't provided, the framework will callthe ``get_absolute_url()`` method on each object as returned by:attr:`~Sitemap.items()`.To specify a protocol other than ``'http'``, use:attr:`~Sitemap.protocol`... attribute:: Sitemap.lastmod**Optional.** Either a method or attribute.If it's a method, it should take one argument -- an object as returnedby :attr:`~Sitemap.items()` -- and return that object's last-modifieddate/time as a :class:`~datetime.datetime`.If it's an attribute, its value should be a :class:`~datetime.datetime`representing the last-modified date/time for *every* object returned by:attr:`~Sitemap.items()`.If all items in a sitemap have a :attr:`~Sitemap.lastmod`, the sitemapgenerated by :func:`views.sitemap` will have a ``Last-Modified``header equal to the latest ``lastmod``. You can activate the:class:`~django.middleware.http.ConditionalGetMiddleware` to makeDjango respond appropriately to requests with an ``If-Modified-Since``header which will prevent sending the sitemap if it hasn't changed... attribute:: Sitemap.paginator**Optional.**This property returns a :class:`~django.core.paginator.Paginator` for:attr:`~Sitemap.items()`. If you generate sitemaps in a batch you maywant to override this as a cached property in order to avoid multiple``items()`` calls... attribute:: Sitemap.changefreq**Optional.** Either a method or attribute.If it's a method, it should take one argument -- an object as returnedby :attr:`~Sitemap.items()` -- and return that object's changefrequency as a string.If it's an attribute, its value should be a string representing thechange frequency of *every* object returned by :attr:`~Sitemap.items()`.Possible values for :attr:`~Sitemap.changefreq`, whether you use amethod or attribute, are:* ``'always'``* ``'hourly'``* ``'daily'``* ``'weekly'``* ``'monthly'``* ``'yearly'``* ``'never'``.. attribute:: Sitemap.priority**Optional.** Either a method or attribute.If it's a method, it should take one argument -- an object as returnedby :attr:`~Sitemap.items()` -- and return that object's priority aseither a string or float.If it's an attribute, its value should be either a string or floatrepresenting the priority of *every* object returned by:attr:`~Sitemap.items()`.Example values for :attr:`~Sitemap.priority`: ``0.4``, ``1.0``. Thedefault priority of a page is ``0.5``. See the `sitemaps.orgdocumentation`_ for more... _sitemaps.org documentation: https://www.sitemaps.org/protocol.html#prioritydef.. attribute:: Sitemap.protocol**Optional.**This attribute defines the protocol (``'http'`` or ``'https'``) of theURLs in the sitemap. If it isn't set, the protocol with which thesitemap was requested is used. If the sitemap is built outside thecontext of a request, the default is ``'http'``... deprecated:: 4.0The default protocol for sitemaps built outside the context of arequest will change from ``'http'`` to ``'https'`` in Django 5.0... attribute:: Sitemap.limit**Optional.**This attribute defines the maximum number of URLs included on each pageof the sitemap. Its value should not exceed the default value of``50000``, which is the upper limit allowed in the `Sitemaps protocol<https://www.sitemaps.org/protocol.html#index>`_... attribute:: Sitemap.i18n**Optional.**A boolean attribute that defines if the URLs of this sitemap shouldbe generated using all of your :setting:`LANGUAGES`. The default is``False``... attribute:: Sitemap.languages**Optional.**A :term:`sequence` of :term:`language codes<language code>` to use forgenerating alternate links when :attr:`~Sitemap.i18n` is enabled.Defaults to :setting:`LANGUAGES`... attribute:: Sitemap.alternates**Optional.**A boolean attribute. When used in conjunction with:attr:`~Sitemap.i18n` generated URLs will each have a list of alternatelinks pointing to other language versions using the `hreflangattribute`_. The default is ``False``... _hreflang attribute: https://developers.google.com/search/docs/advanced/crawling/localized-versions.. attribute:: Sitemap.x_default**Optional.**A boolean attribute. When ``True`` the alternate links generated by:attr:`~Sitemap.alternates` will contain a ``hreflang="x-default"``fallback entry with a value of :setting:`LANGUAGE_CODE`. The default is``False``... method:: Sitemap.get_latest_lastmod().. versionadded:: 4.1**Optional.** A method that returns the latest value returned by:attr:`~Sitemap.lastmod`. This function is used to add the ``lastmod``attribute to :ref:`Sitemap index contextvariables<sitemap-index-context-variables>`.By default :meth:`~Sitemap.get_latest_lastmod` returns:* If :attr:`~Sitemap.lastmod` is an attribute::attr:`~Sitemap.lastmod`.* If :attr:`~Sitemap.lastmod` is a method:The latest ``lastmod`` returned by calling the method with allitems returned by :meth:`Sitemap.items`.Shortcuts=========The sitemap framework provides a convenience class for a common case:.. class:: GenericSitemap(info_dict, priority=None, changefreq=None, protocol=None)The :class:`django.contrib.sitemaps.GenericSitemap` class allows you tocreate a sitemap by passing it a dictionary which has to contain at leasta ``queryset`` entry. This queryset will be used to generate the itemsof the sitemap. It may also have a ``date_field`` entry thatspecifies a date field for objects retrieved from the ``queryset``.This will be used for the :attr:`~Sitemap.lastmod` attribute and:meth:`~Sitemap.get_latest_lastmod` methods in the in thegenerated sitemap.The :attr:`~Sitemap.priority`, :attr:`~Sitemap.changefreq`,and :attr:`~Sitemap.protocol` keyword arguments allow specifying theseattributes for all URLs.Example-------Here's an example of a :doc:`URLconf </topics/http/urls>` using:class:`GenericSitemap`::from django.contrib.sitemaps import GenericSitemapfrom django.contrib.sitemaps.views import sitemapfrom django.urls import pathfrom blog.models import Entryinfo_dict = {'queryset': Entry.objects.all(),'date_field': 'pub_date',}urlpatterns = [# some generic view using info_dict# ...# the sitemappath('sitemap.xml', sitemap,{'sitemaps': {'blog': GenericSitemap(info_dict, priority=0.6)}},name='django.contrib.sitemaps.views.sitemap'),].. _URLconf: ../url_dispatch/Sitemap for static views========================Often you want the search engine crawlers to index views which are neitherobject detail pages nor flatpages. The solution is to explicitly list URLnames for these views in ``items`` and call :func:`~django.urls.reverse` inthe ``location`` method of the sitemap. For example::# sitemaps.pyfrom django.contrib import sitemapsfrom django.urls import reverseclass StaticViewSitemap(sitemaps.Sitemap):priority = 0.5changefreq = 'daily'def items(self):return ['main', 'about', 'license']def location(self, item):return reverse(item)# urls.pyfrom django.contrib.sitemaps.views import sitemapfrom django.urls import pathfrom .sitemaps import StaticViewSitemapfrom . import viewssitemaps = {'static': StaticViewSitemap,}urlpatterns = [path('', views.main, name='main'),path('about/', views.about, name='about'),path('license/', views.license, name='license'),# ...path('sitemap.xml', sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap')]Creating a sitemap index========================.. function:: views.index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap')The sitemap framework also has the ability to create a sitemap index thatreferences individual sitemap files, one per each section defined in your``sitemaps`` dictionary. The only differences in usage are:* You use two views in your URLconf: :func:`django.contrib.sitemaps.views.index`and :func:`django.contrib.sitemaps.views.sitemap`.* The :func:`django.contrib.sitemaps.views.sitemap` view should take a``section`` keyword argument.Here's what the relevant URLconf lines would look like for the example above::from django.contrib.sitemaps import viewsurlpatterns = [path('sitemap.xml', views.index, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.index'),path('sitemap-<section>.xml', views.sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap'),]This will automatically generate a :file:`sitemap.xml` file that referencesboth :file:`sitemap-flatpages.xml` and :file:`sitemap-blog.xml`. The:class:`~django.contrib.sitemaps.Sitemap` classes and the ``sitemaps``dict don't change at all.If all sitemaps have a ``lastmod`` returned by:meth:`Sitemap.get_latest_lastmod` the sitemap index will have a``Last-Modified`` header equal to the latest ``lastmod``.You should create an index file if one of your sitemaps has more than 50,000URLs. In this case, Django will automatically paginate the sitemap, and theindex will reflect that.If you're not using the vanilla sitemap view -- for example, if it's wrappedwith a caching decorator -- you must name your sitemap view and pass``sitemap_url_name`` to the index view::from django.contrib.sitemaps import views as sitemaps_viewsfrom django.views.decorators.cache import cache_pageurlpatterns = [path('sitemap.xml',cache_page(86400)(sitemaps_views.index),{'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),path('sitemap-<section>.xml',cache_page(86400)(sitemaps_views.sitemap),{'sitemaps': sitemaps}, name='sitemaps'),].. versionchanged:: 4.1Use of the ``Last-Modified`` header was added.Template customization======================If you wish to use a different template for each sitemap or sitemap indexavailable on your site, you may specify it by passing a ``template_name``parameter to the ``sitemap`` and ``index`` views via the URLconf::from django.contrib.sitemaps import viewsurlpatterns = [path('custom-sitemap.xml', views.index, {'sitemaps': sitemaps,'template_name': 'custom_sitemap.html'}, name='django.contrib.sitemaps.views.index'),path('custom-sitemap-<section>.xml', views.sitemap, {'sitemaps': sitemaps,'template_name': 'custom_sitemap.html'}, name='django.contrib.sitemaps.views.sitemap'),]These views return :class:`~django.template.response.TemplateResponse`instances which allow you to easily customize the response data beforerendering. For more details, see the :doc:`TemplateResponse documentation</ref/template-response>`.Context variables-----------------When customizing the templates for the:func:`~django.contrib.sitemaps.views.index` and:func:`~django.contrib.sitemaps.views.sitemap` views, you can rely on thefollowing context variables... _sitemap-index-context-variables:Index-----The variable ``sitemaps`` is a list of objects containing the ``location`` and``lastmod`` attribute for each of the sitemaps. Each URL exposes the followingattributes:- ``location``: The location (url & page) of the sitemap.- ``lastmod``: Populated by the :meth:`~Sitemap.get_latest_lastmod`method for each sitemap... versionchanged:: 4.1The context was changed to a list of objects with ``location`` and optional``lastmod`` attributes.Sitemap-------The variable ``urlset`` is a list of URLs that should appear in thesitemap. Each URL exposes attributes as defined in the:class:`~django.contrib.sitemaps.Sitemap` class:- ``alternates``- ``changefreq``- ``item``- ``lastmod``- ``location``- ``priority``The ``alternates`` attribute is available when :attr:`~Sitemap.i18n` and:attr:`~Sitemap.alternates` are enabled. It is a list of other languageversions, including the optional :attr:`~Sitemap.x_default` fallback, for eachURL. Each alternate is a dictionary with ``location`` and ``lang_code`` keys.The ``item`` attribute has been added for each URL to allow more flexiblecustomization of the templates, such as `Google news sitemaps`_. AssumingSitemap's :attr:`~Sitemap.items()` would return a list of items with``publication_data`` and a ``tags`` field something like this wouldgenerate a Google News compatible sitemap:.. code-block:: xml+django<?xml version="1.0" encoding="UTF-8"?><urlsetxmlns="https://www.sitemaps.org/schemas/sitemap/0.9"xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">{% spaceless %}{% for url in urlset %}<url><loc>{{ url.location }}</loc>{% if url.lastmod %}<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>{% endif %}{% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %}{% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %}<news:news>{% if url.item.publication_date %}<news:publication_date>{{ url.item.publication_date|date:"Y-m-d" }}</news:publication_date>{% endif %}{% if url.item.tags %}<news:keywords>{{ url.item.tags }}</news:keywords>{% endif %}</news:news></url>{% endfor %}{% endspaceless %}</urlset>.. _`Google news sitemaps`: https://support.google.com/news/publisher-center/answer/9606710Pinging Google==============You may want to "ping" Google when your sitemap changes, to let it know toreindex your site. The sitemaps framework provides a function to do justthat: :func:`django.contrib.sitemaps.ping_google()`... function:: ping_google(sitemap_url=None, ping_url=PING_URL, sitemap_uses_https=True)``ping_google`` takes these optional arguments:* ``sitemap_url`` - The absolute path to your site's sitemap (e.g.,:file:`'/sitemap.xml'`).If this argument isn't provided, ``ping_google`` will perform a reverselookup in your URLconf, for URLs named``'django.contrib.sitemaps.views.index'`` and then``'django.contrib.sitemaps.views.sitemap'`` (without further arguments) toautomatically determine the sitemap URL.* ``ping_url`` - Defaults to Google's Ping Tool:https://www.google.com/webmasters/tools/ping.* ``sitemap_uses_https`` - Set to ``False`` if your site uses ``http``rather than ``https``.:func:`ping_google` raises the exception``django.contrib.sitemaps.SitemapNotFound`` if it cannot determine yoursitemap URL... admonition:: Register with Google first!The :func:`ping_google` command only works if you have registered yoursite with `Google Search Console`_... _`Google Search Console`: https://search.google.com/search-console/welcomeOne useful way to call :func:`ping_google` is from a model's ``save()``method::from django.contrib.sitemaps import ping_googleclass Entry(models.Model):# ...def save(self, force_insert=False, force_update=False):super().save(force_insert, force_update)try:ping_google()except Exception:# Bare 'except' because we could get a variety# of HTTP-related exceptions.passA more efficient solution, however, would be to call :func:`ping_google` from acron script, or some other scheduled task. The function makes an HTTP requestto Google's servers, so you may not want to introduce that network overheadeach time you call ``save()``.Pinging Google via ``manage.py``--------------------------------.. django-admin:: ping_google [sitemap_url]Once the sitemaps application is added to your project, you may alsoping Google using the ``ping_google`` management command::python manage.py ping_google [/sitemap.xml].. django-admin-option:: --sitemap-uses-httpUse this option if your sitemap uses ``http`` rather than ``https``.