The sitemap framework

    A sitemap is an XML file on your website that tells search-engine indexers how frequently your pages change and how “important” certain pages are in relation to other pages on your site. This information helps search engines index your site.

    The Django sitemap framework automates the creation of this XML file by letting you express this information in Python code.

    It works much like Django’s syndication framework. To create a sitemap, write a class and point to it in your URLconf.

    Installation

    To install the sitemap app, follow these steps:

    1. Add 'django.contrib.sitemaps' to your INSTALLED_APPS setting.
    2. Make sure your setting contains a DjangoTemplates backend whose APP_DIRS options is set to True. It’s in there by default, so you’ll only need to change this if you’ve changed that setting.
    3. Make sure you’ve installed the sites framework.

    (Note: The sitemap application doesn’t install any database tables. The only reason it needs to go into is so that the Loader() template loader can find the default templates.)

    Initialization

    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 URLconf:

    This tells Django to build a sitemap when a client accesses /sitemap.xml.

    The name of the sitemap file is not important, but the location is. Search engines will only index links in your sitemap for the current URL level and below. For instance, if sitemap.xml lives in your root directory, it may reference any URL in your site. However, if your sitemap lives at /content/sitemap.xml, it may only reference URLs that begin with /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 (e.g., BlogSitemap or NewsSitemap). It may also map to an instance of a Sitemap class (e.g., BlogSitemap(some_var)).

    A class is a Python class that represents a “section” of entries in your sitemap. For example, one Sitemap class could represent all the entries of your blog, while another could represent all of the events in your events calendar.

    In the simplest case, all these sections get lumped together into one sitemap.xml, but it’s also possible to use the framework to generate a sitemap index that references individual sitemap files, one per section. (See below.)

    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 your sitemap to include all the links to your individual blog entries. Here’s how your sitemap class might look:

    1. from django.contrib.sitemaps import Sitemap
    2. from blog.models import Entry
    3. class BlogSitemap(Sitemap):
    4. changefreq = "never"
    5. priority = 0.5
    6. def items(self):
    7. return Entry.objects.filter(is_draft=False)
    8. def lastmod(self, obj):
    9. return obj.pub_date

    Note:

    • changefreq and are class attributes corresponding to <changefreq> and <priority> elements, respectively. They can be made callable as functions, as lastmod was in the example.
    • is a method that returns a sequence or QuerySet of objects. The objects returned will get passed to any callable methods corresponding to a sitemap property (, lastmod, , and priority).
    • should return a datetime.
    • There is no method in this example, but you can provide it in order to specify the URL for your object. By default, location() calls get_absolute_url() on each object and returns the result.

    Sitemap class reference

    class Sitemap

    A Sitemap class can define the following methods/attributes:

    • items

      Required. A method that returns a 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 , lastmod(), and priority() methods.

    • location

      Optional. Either a method or attribute.

      If it’s a method, it should return the absolute path for a given object as returned by .

      If it’s an attribute, its value should be a string representing an absolute path to use for every object returned by items().

      In both cases, “absolute path” means a URL that doesn’t include the protocol or domain. Examples:

      • Good: '/foo/bar/'
      • Bad: 'example.com/foo/bar/'
      • Bad: 'https://example.com/foo/bar/'

      If isn’t provided, the framework will call the get_absolute_url() method on each object as returned by items().

      To specify a protocol other than 'http', use .

    • lastmod

      Optional. Either a method or attribute.

      If it’s a method, it should take one argument – an object as returned by items() – and return that object’s last-modified date/time as a .

      If it’s an attribute, its value should be a datetime representing the last-modified date/time for every object returned by .

      If all items in a sitemap have a lastmod, the sitemap generated by will have a Last-Modified header equal to the latest lastmod. You can activate the ConditionalGetMiddleware to make Django respond appropriately to requests with an If-Modified-Since header which will prevent sending the sitemap if it hasn’t changed.

    • paginator

      Optional.

      This property returns a for items(). If you generate sitemaps in a batch you may want to override this as a cached property in order to avoid multiple items() calls.

    • changefreq

      If it’s a method, it should take one argument – an object as returned by – and return that object’s change frequency as a string.

      If it’s an attribute, its value should be a string representing the change frequency of every object returned by items().

      Possible values for , whether you use a method or attribute, are:

      • 'always'
      • 'hourly'
      • 'daily'
      • 'monthly'
      • 'yearly'
      • 'never'
    • priority

      Optional. Either a method or attribute.

      If it’s a method, it should take one argument – an object as returned by items() – and return that object’s priority as either a string or float.

      If it’s an attribute, its value should be either a string or float representing the priority of every object returned by .

      Example values for priority: 0.4, 1.0. The default priority of a page is 0.5. See the for more.

    • protocol

      Optional.

      This attribute defines the protocol ('http' or 'https') of the URLs in the sitemap. If it isn’t set, the protocol with which the sitemap was requested is used. If the sitemap is built outside the context of a request, the default is 'http'.

      Deprecated since version 4.0: The default protocol for sitemaps built outside the context of a request will change from 'http' to in Django 5.0.

    • limit

      Optional.

      This attribute defines the maximum number of URLs included on each page of the sitemap. Its value should not exceed the default value of 50000, which is the upper limit allowed in the Sitemaps protocol.

    • i18n

      Optional.

      A boolean attribute that defines if the URLs of this sitemap should be generated using all of your . The default is False.

    • languages

      Optional.

      A sequence of to use for generating alternate links when i18n is enabled. Defaults to .

    • alternates

      Optional.

      A boolean attribute. When used in conjunction with i18n generated URLs will each have a list of alternate links pointing to other language versions using the . The default is False.

    • x_default

      Optional.

      A boolean attribute. When True the alternate links generated by alternates will contain a hreflang="x-default" fallback entry with a value of . The default is False.

    • get_latest_lastmod()

      New in Django 4.1.

      Optional. A method that returns the latest value returned by lastmod. This function is used to add the lastmod attribute to .

      By default get_latest_lastmod() returns:

      • If is an attribute: lastmod.
      • If is a method: The latest lastmod returned by calling the method with all items returned by Sitemap.items().

    The sitemap framework provides a convenience class for a common case:

    class GenericSitemap(info_dict, priority=None, changefreq=None, protocol=None)

    The class allows you to create a sitemap by passing it a dictionary which has to contain at least a queryset entry. This queryset will be used to generate the items of the sitemap. It may also have a date_field entry that specifies a date field for objects retrieved from the queryset. This will be used for the lastmod attribute and methods in the in the generated sitemap.

    The priority, , and protocol keyword arguments allow specifying these attributes for all URLs.

    1. from django.contrib.sitemaps import GenericSitemap
    2. from django.contrib.sitemaps.views import sitemap
    3. from django.urls import path
    4. from blog.models import Entry
    5. info_dict = {
    6. 'queryset': Entry.objects.all(),
    7. 'date_field': 'pub_date',
    8. }
    9. urlpatterns = [
    10. # some generic view using info_dict
    11. # ...
    12. # the sitemap
    13. path('sitemap.xml', sitemap,
    14. {'sitemaps': {'blog': GenericSitemap(info_dict, priority=0.6)}},
    15. name='django.contrib.sitemaps.views.sitemap'),
    16. ]

    Sitemap for static views

    Often you want the search engine crawlers to index views which are neither object detail pages nor flatpages. The solution is to explicitly list URL names for these views in items and call reverse() in the location method of the sitemap. For example:

    Creating a sitemap index

    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 that references individual sitemap files, one per each section defined in your sitemaps dictionary. The only differences in usage are:

    Here’s what the relevant URLconf lines would look like for the example above:

    1. from django.contrib.sitemaps import views
    2. urlpatterns = [
    3. path('sitemap.xml', views.index, {'sitemaps': sitemaps},
    4. name='django.contrib.sitemaps.views.index'),
    5. path('sitemap-<section>.xml', views.sitemap, {'sitemaps': sitemaps},
    6. name='django.contrib.sitemaps.views.sitemap'),
    7. ]

    This will automatically generate a sitemap.xml file that references both sitemap-flatpages.xml and sitemap-blog.xml. The classes and the sitemaps dict don’t change at all.

    If all sitemaps have a lastmod returned by 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,000 URLs. In this case, Django will automatically paginate the sitemap, and the index will reflect that.

    If you’re not using the vanilla sitemap view – for example, if it’s wrapped with a caching decorator – you must name your sitemap view and pass sitemap_url_name to the index view:

    1. from django.contrib.sitemaps import views as sitemaps_views
    2. from django.views.decorators.cache import cache_page
    3. urlpatterns = [
    4. cache_page(86400)(sitemaps_views.index),
    5. {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),
    6. path('sitemap-<section>.xml',
    7. cache_page(86400)(sitemaps_views.sitemap),
    8. {'sitemaps': sitemaps}, name='sitemaps'),
    9. ]

    Changed in Django 4.1:

    Use of the Last-Modified header was added.

    If you wish to use a different template for each sitemap or sitemap index available on your site, you may specify it by passing a template_name parameter to the sitemap and views via the URLconf:

    These views return instances which allow you to easily customize the response data before rendering. For more details, see the TemplateResponse documentation.

    When customizing the templates for the and sitemap() views, you can rely on the following context variables.

    The variable sitemaps is a list of objects containing the location and lastmod attribute for each of the sitemaps. Each URL exposes the following attributes:

    • location: The location (url & page) of the sitemap.
    • lastmod: Populated by the method for each sitemap.

    Changed in Django 4.1:

    The context was changed to a list of objects with location and optional lastmod attributes.

    The variable urlset is a list of URLs that should appear in the sitemap. Each URL exposes attributes as defined in the Sitemap class:

    • alternates
    • changefreq
    • item
    • lastmod
    • location
    • priority

    The alternates attribute is available when and alternates are enabled. It is a list of other language versions, including the optional fallback, for each URL. Each alternate is a dictionary with location and lang_code keys.

    The item attribute has been added for each URL to allow more flexible customization of the templates, such as Google news sitemaps. Assuming Sitemap’s would return a list of items with publication_data and a tags field something like this would generate a Google News compatible sitemap:

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <urlset
    3. xmlns="https://www.sitemaps.org/schemas/sitemap/0.9"
    4. xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
    5. {% spaceless %}
    6. {% for url in urlset %}
    7. <url>
    8. <loc>{{ url.location }}</loc>
    9. {% if url.lastmod %}<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>{% endif %}
    10. {% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %}
    11. {% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %}
    12. <news:news>
    13. {% if url.item.publication_date %}<news:publication_date>{{ url.item.publication_date|date:"Y-m-d" }}</news:publication_date>{% endif %}
    14. {% if url.item.tags %}<news:keywords>{{ url.item.tags }}</news:keywords>{% endif %}
    15. </news:news>
    16. </url>
    17. {% endfor %}
    18. {% endspaceless %}
    19. </urlset>

    Pinging Google

    You may want to “ping” Google when your sitemap changes, to let it know to reindex your site. The sitemaps framework provides a function to do just that: .

    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., '/sitemap.xml').

      If this argument isn’t provided, ping_google will perform a reverse lookup in your URLconf, for URLs named 'django.contrib.sitemaps.views.index' and then 'django.contrib.sitemaps.views.sitemap' (without further arguments) to automatically 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.

    raises the exception django.contrib.sitemaps.SitemapNotFound if it cannot determine your sitemap URL.

    Register with Google first!

    The ping_google() command only works if you have registered your site with .

    One useful way to call ping_google() is from a model’s save() method:

    1. from django.contrib.sitemaps import ping_google
    2. class Entry(models.Model):
    3. # ...
    4. def save(self, force_insert=False, force_update=False):
    5. super().save(force_insert, force_update)
    6. try:
    7. ping_google()
    8. except Exception:
    9. # Bare 'except' because we could get a variety
    10. pass

    A more efficient solution, however, would be to call from a cron script, or some other scheduled task. The function makes an HTTP request to Google’s servers, so you may not want to introduce that network overhead each time you call save().

    django-admin ping_google [sitemap_url]

    Once the sitemaps application is added to your project, you may also ping Google using the ping_google management command:

    --sitemap-uses-http

    Use this option if your sitemap uses http rather than https.