sitemaps.txt 19 KB

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