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 yourINSTALLED_APPS
setting. - Make sure your
TEMPLATES
setting contains aDjangoTemplates
backend whoseAPP_DIRS
options is set toTrue
. 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
sites framework
.(Note: The sitemap application doesn't install any database tables. The onlyreason it needs to go intoINSTALLED_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:
- from django.contrib.sitemaps.views import sitemap
- path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
- 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:
- from django.contrib.sitemaps import Sitemap
- from blog.models import Entry
- class BlogSitemap(Sitemap):
- changefreq = "never"
- priority = 0.5
- def items(self):
- return Entry.objects.filter(is_draft=False)
- def lastmod(self, obj):
- return obj.pub_date
Note:
changefreq
andpriority
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 adatetime
.- There is no
location
method in this example, but youcan provide it in order to specify the URL for your object. By default,location()
callsget_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:
- Good: <code>'/foo/bar/'</code>
- Bad: <code>'example.com/foo/bar/'</code>
- Bad: <code>'https://example.com/foo/bar/'</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
.
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 datetime
representing 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-Modified
header equal to the latest lastmod
. You can activate theConditionalGetMiddleware
to makeDjango respond appropriately to requests with an If-Modified-Since
header which will prevent sending the sitemap if it hasn't changed.
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:
- <code>'always'</code>
- <code>'hourly'</code>
- <code>'daily'</code>
- <code>'weekly'</code>
- <code>'monthly'</code>
- <code>'yearly'</code>
- <code>'never'</code>
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.
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'
.
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.
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 leastaqueryset
entry. This queryset will be used to generate the itemsof the sitemap. It may also have adate_field
entry thatspecifies a date field for objects retrieved from thequeryset
.This will be used for thelastmod
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
:
- from django.contrib.sitemaps import GenericSitemap
- from django.contrib.sitemaps.views import sitemap
- from django.urls import path
- from blog.models import Entry
- info_dict = {
- 'queryset': Entry.objects.all(),
- 'date_field': 'pub_date',
- }
- urlpatterns = [
- # some generic view using info_dict
- # ...
- # the sitemap
- path('sitemap.xml', sitemap,
- {'sitemaps': {'blog': GenericSitemap(info_dict, priority=0.6)}},
- name='django.contrib.sitemaps.views.sitemap'),
- ]
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:
- # sitemaps.py
- from django.contrib import sitemaps
- from django.urls import reverse
- class StaticViewSitemap(sitemaps.Sitemap):
- priority = 0.5
- changefreq = 'daily'
- def items(self):
- return ['main', 'about', 'license']
- def location(self, item):
- return reverse(item)
- # urls.py
- from django.contrib.sitemaps.views import sitemap
- from django.urls import path
- from .sitemaps import StaticViewSitemap
- from . import views
- sitemaps = {
- '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
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:
django.contrib.sitemaps.views.index()
anddjango.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:
- from django.contrib.sitemaps import views
- urlpatterns = [
- path('sitemap.xml', views.index, {'sitemaps': sitemaps}),
- path('sitemap-<section>.xml', views.sitemap, {'sitemaps': sitemaps},
- name='django.contrib.sitemaps.views.sitemap'),
- ]
This will automatically generate a sitemap.xml
file that referencesboth sitemap-flatpages.xml
and sitemap-blog.xml
. TheSitemap
classes and the sitemaps
dict 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:
- from django.contrib.sitemaps import views as sitemaps_views
- from django.views.decorators.cache import cache_page
- urlpatterns = [
- 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'),
- ]
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 views
- urlpatterns = [
- path('custom-sitemap.xml', views.index, {
- 'sitemaps': sitemaps,
- 'template_name': 'custom_sitemap.html'
- }),
- path('custom-sitemap-<section>.xml', views.sitemap, {
- 'sitemaps': sitemaps,
- 'template_name': 'custom_sitemap.html'
- }, name='django.contrib.sitemaps.views.sitemap'),
- ]
These views return TemplateResponse
instances 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
priority
Theitem
attribute has been added for each URL to allow more flexiblecustomization of the templates, such as Google news sitemaps. AssumingSitemap'sitems()
would return a list of items withpublication_data
and atags
field something like this wouldgenerate a Google News compatible sitemap:
- <?xml version="1.0" encoding="UTF-8"?>
- <urlset
- xmlns="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>
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:
- from django.contrib.sitemaps import ping_google
- class 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.
- 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:
- python manage.py ping_google [/sitemap.xml]