sitemaps.txt 19 KB

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