sitemaps.txt 19 KB

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