The sitemap framework

Django comes with a high-level sitemap-generating framework that makescreating sitemap XML files easy.

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 syndication framework. To create a sitemap, just write aSitemap class and point to it in yourURLconf.

Installation

To install the sitemap app, follow these steps:

  • Add 'django.contrib.sitemaps' to your INSTALLED_APPSsetting.
  • Make sure your TEMPLATES setting contains a DjangoTemplatesbackend 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 thesites framework.(Note: The sitemap application doesn't install any database tables. The onlyreason it needs to go into INSTALLED_APPS is so that theLoader() templateloader 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 yourURLconf:
  1. from django.contrib.sitemaps.views import sitemap
  2.  
  3. path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
  4. name='django.contrib.sitemaps.views.sitemap')

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. Searchengines will only index links in your sitemap for the current URL level andbelow. For instance, if sitemap.xml lives in your root directory, it mayreference 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 Sitemap class(e.g., BlogSitemap or NewsSitemap). It may also map to an instance ofa Sitemap class (e.g.,BlogSitemap(some_var)).

Sitemap classes

A Sitemap class is a simple Pythonclass that represents a "section" of entries in your sitemap. For example,one Sitemap class could representall the entries of your Weblog, while another could represent all of theevents in your events calendar.

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

Sitemap classes must subclassdjango.contrib.sitemaps.Sitemap. They can live anywhere in your codebase.

A simple 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:

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

Note:

  • changefreq and priority are classattributes corresponding to <changefreq> and <priority> elements,respectively. They can be made callable as functions, aslastmod was in the example.
  • items() is simply a method that returns a list ofobjects. The objects returned will get passed to any callable methodscorresponding to a sitemap property (location,lastmod, changefreq, andpriority).
  • lastmod should return a datetime.
  • There is no location method in this example, but youcan provide it in order to specify the URL for your object. By default,location() calls get_absolute_url() on each objectand returns the result.

Sitemap class reference

  • class Sitemap[source]
  • A Sitemap class can define the following methods/attributes:

    • items[source]
    • Required. A method that returns a list of objects. The frameworkdoesn't care what type of objects they are; all that matters is thatthese objects get passed to the location(),lastmod(), changefreq() andpriority() methods.

    • location[source]

    • Optional. Either a method or attribute.

If it's a method, it should return the absolute path for a given objectas returned by items().

If it's an attribute, its value should be a string representing anabsolute path to use for every object returned byitems().

In both cases, "absolute path" means a URL that doesn't include theprotocol or domain. Examples:

  1. - Good: <code>&#39;/foo/bar/&#39;</code>
  2. - Bad: <code>&#39;example.com/foo/bar/&#39;</code>
  3. - Bad: <code>&#39;https://example.com/foo/bar/&#39;</code>

If location isn't provided, the framework will callthe get_absolute_url() method on each object as returned byitems().

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

  • lastmod
  • Optional. Either a method or attribute.

If it's a method, it should take one argument — an object as returnedby items() — and return that object's last-modifieddate/time as a datetime.

If it's an attribute, its value should be a datetimerepresenting the last-modified date/time for every object returned byitems().

If all items in a sitemap have a lastmod, the sitemapgenerated by views.sitemap() will have a Last-Modifiedheader equal to the latest lastmod. You can activate theConditionalGetMiddleware to makeDjango respond appropriately to requests with an If-Modified-Sinceheader which will prevent sending the sitemap if it hasn't changed.

  • changefreq
  • Optional. Either a method or attribute.

If it's a method, it should take one argument — an object as returnedby 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 items().

Possible values for changefreq, whether you use amethod or attribute, are:

  1. - <code>&#39;always&#39;</code>
  2. - <code>&#39;hourly&#39;</code>
  3. - <code>&#39;daily&#39;</code>
  4. - <code>&#39;weekly&#39;</code>
  5. - <code>&#39;monthly&#39;</code>
  6. - <code>&#39;yearly&#39;</code>
  7. - <code>&#39;never&#39;</code>
  • priority
  • Optional. Either a method or attribute.

If it's a method, it should take one argument — an object as returnedby 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 byitems().

Example values for priority: 0.4, 1.0. Thedefault priority of a page is 0.5. See the sitemaps.orgdocumentation for more.

  • 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'.

  • limit
  • Optional.

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

  • i18n
  • Optional.

A boolean attribute that defines if the URLs of this sitemap shouldbe generated using all of your LANGUAGES. The default isFalse.

Shortcuts

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

  • class GenericSitemap(info_dict, priority=None, changefreq=None, protocol=None)[source]
  • The 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 lastmod attribute in thegenerated sitemap.

The priority, changefreq,and protocol keyword arguments allow specifying theseattributes for all URLs.

New in Django 2.0:The protocol keyword argument was added.

Example

Here's an example of a URLconf usingGenericSitemap:

  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.  
  6. info_dict = {
  7. 'queryset': Entry.objects.all(),
  8. 'date_field': 'pub_date',
  9. }
  10.  
  11. urlpatterns = [
  12. # some generic view using info_dict
  13. # ...
  14.  
  15. # the sitemap
  16. path('sitemap.xml', sitemap,
  17. {'sitemaps': {'blog': GenericSitemap(info_dict, priority=0.6)}},
  18. name='django.contrib.sitemaps.views.sitemap'),
  19. ]

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 reverse() inthe location method of the sitemap. For example:

  1. # sitemaps.py
  2. from django.contrib import sitemaps
  3. from django.urls import reverse
  4.  
  5. class StaticViewSitemap(sitemaps.Sitemap):
  6. priority = 0.5
  7. changefreq = 'daily'
  8.  
  9. def items(self):
  10. return ['main', 'about', 'license']
  11.  
  12. def location(self, item):
  13. return reverse(item)
  14.  
  15. # urls.py
  16. from django.contrib.sitemaps.views import sitemap
  17. from django.urls import path
  18.  
  19. from .sitemaps import StaticViewSitemap
  20. from . import views
  21.  
  22. sitemaps = {
  23. 'static': StaticViewSitemap,
  24. }
  25.  
  26. urlpatterns = [
  27. path('', views.main, name='main'),
  28. path('about/', views.about, name='about'),
  29. path('license/', views.license, name='license'),
  30. # ...
  31. path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
  32. name='django.contrib.sitemaps.views.sitemap')
  33. ]

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

  • You use two views in your URLconf: django.contrib.sitemaps.views.index()and django.contrib.sitemaps.views.sitemap().

  • The django.contrib.sitemaps.views.sitemap() view should take asection keyword argument.Here's what the relevant URLconf lines would look like for the example above:
  1. from django.contrib.sitemaps import views
  2.  
  3. urlpatterns = [
  4. path('sitemap.xml', views.index, {'sitemaps': sitemaps}),
  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 referencesboth sitemap-flatpages.xml and sitemap-blog.xml. TheSitemap classes and the sitemapsdict don't change at all.

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 passsitemap_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.  
  4. urlpatterns = [
  5. path('sitemap.xml',
  6. cache_page(86400)(sitemaps_views.index),
  7. {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),
  8. path('sitemap-<section>.xml',
  9. cache_page(86400)(sitemaps_views.sitemap),
  10. {'sitemaps': sitemaps}, name='sitemaps'),
  11. ]

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_nameparameter to the sitemap and index views via the URLconf:

  1. from django.contrib.sitemaps import views
  2.  
  3. urlpatterns = [
  4. path('custom-sitemap.xml', views.index, {
  5. 'sitemaps': sitemaps,
  6. 'template_name': 'custom_sitemap.html'
  7. }),
  8. path('custom-sitemap-<section>.xml', views.sitemap, {
  9. 'sitemaps': sitemaps,
  10. 'template_name': 'custom_sitemap.html'
  11. }, name='django.contrib.sitemaps.views.sitemap'),
  12. ]

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

Context variables

When customizing the templates for theindex() andsitemap() views, you can rely on thefollowing context variables.

Index

The variable sitemaps is a list of absolute URLs to each of the sitemaps.

Sitemap

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

  • changefreq
  • item
  • lastmod
  • location
  • priorityThe item attribute has been added for each URL to allow more flexiblecustomization of the templates, such as Google news sitemaps. AssumingSitemap's items() would return a list of items withpublication_data and a tags field something like this wouldgenerate 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 toreindex your site. The sitemaps framework provides a function to do justthat: django.contrib.sitemaps.ping_google().

  • ping_google()[source]
  • ping_google() takes an optional argument, sitemap_url,which should be the absolute path to your site's sitemap (e.g.,'/sitemap.xml'). If this argument isn't provided,ping_google() will attempt to figure out yoursitemap by performing a reverse looking in your URLconf.

ping_google() raises the exceptiondjango.contrib.sitemaps.SitemapNotFound if it cannot determine yoursitemap URL.

Register with Google first!

The ping_google() command only works if you have registered yoursite with Google Webmaster Tools.

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

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

A more efficient solution, however, would be to call 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:
  1. python manage.py ping_google [/sitemap.xml]