sitemaps.txt 17 KB

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