sitemaps.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 mysite.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 URL for a given object as
  108. returned by :attr:`~Sitemap.items()`.
  109. If it's an attribute, its value should be a string representing an absolute URL
  110. to use for *every* object returned by :attr:`~Sitemap.items()`.
  111. In both cases, "absolute URL" means a URL that doesn't include the protocol or
  112. domain. Examples:
  113. * Good: :file:`'/foo/bar/'`
  114. * Bad: :file:`'example.com/foo/bar/'`
  115. * Bad: :file:`'http://example.com/foo/bar/'`
  116. If :attr:`~Sitemap.location` isn't provided, the framework will call the
  117. ``get_absolute_url()`` method on each object as returned by
  118. :attr:`~Sitemap.items()`.
  119. .. attribute:: Sitemap.lastmod
  120. **Optional.** Either a method or attribute.
  121. If it's a method, it should take one argument -- an object as returned by
  122. :attr:`~Sitemap.items()` -- and return that object's last-modified date/time, as a Python
  123. ``datetime.datetime`` object.
  124. If it's an attribute, its value should be a Python ``datetime.datetime`` object
  125. representing the last-modified date/time for *every* object returned by
  126. :attr:`~Sitemap.items()`.
  127. .. attribute:: Sitemap.changefreq
  128. **Optional.** Either a method or attribute.
  129. If it's a method, it should take one argument -- an object as returned by
  130. :attr:`~Sitemap.items()` -- and return that object's change frequency, as a Python string.
  131. If it's an attribute, its value should be a string representing the change
  132. frequency of *every* object returned by :attr:`~Sitemap.items()`.
  133. Possible values for :attr:`~Sitemap.changefreq`, whether you use a method or attribute, are:
  134. * ``'always'``
  135. * ``'hourly'``
  136. * ``'daily'``
  137. * ``'weekly'``
  138. * ``'monthly'``
  139. * ``'yearly'``
  140. * ``'never'``
  141. .. method:: Sitemap.priority
  142. **Optional.** Either a method or attribute.
  143. If it's a method, it should take one argument -- an object as returned by
  144. :attr:`~Sitemap.items()` -- and return that object's priority, as either a string or float.
  145. If it's an attribute, its value should be either a string or float representing
  146. the priority of *every* object returned by :attr:`~Sitemap.items()`.
  147. Example values for :attr:`~Sitemap.priority`: ``0.4``, ``1.0``. The default priority of a
  148. page is ``0.5``. See the `sitemaps.org documentation`_ for more.
  149. .. _sitemaps.org documentation: http://www.sitemaps.org/protocol.html#prioritydef
  150. Shortcuts
  151. =========
  152. The sitemap framework provides a couple convenience classes for common cases:
  153. .. class:: FlatPageSitemap
  154. The :class:`django.contrib.sitemaps.FlatPageSitemap` class looks at all
  155. publicly visible :mod:`flatpages <django.contrib.flatpages>`
  156. defined for the current :setting:`SITE_ID` (see the
  157. :mod:`sites documentation <django.contrib.sites>`) and
  158. creates an entry in the sitemap. These entries include only the
  159. :attr:`~Sitemap.location` attribute -- not :attr:`~Sitemap.lastmod`,
  160. :attr:`~Sitemap.changefreq` or :attr:`~Sitemap.priority`.
  161. .. class:: GenericSitemap
  162. The :class:`django.contrib.sitemaps.GenericSitemap` class works with any
  163. :doc:`generic views </ref/generic-views>` you already have.
  164. To use it, create an instance, passing in the same :data:`info_dict` you pass to
  165. the generic views. The only requirement is that the dictionary have a
  166. :data:`queryset` entry. It may also have a :data:`date_field` entry that specifies a
  167. date field for objects retrieved from the :data:`queryset`. This will be used for
  168. the :attr:`~Sitemap.lastmod` attribute in the generated sitemap. You may
  169. also pass :attr:`~Sitemap.priority` and :attr:`~Sitemap.changefreq`
  170. keyword arguments to the :class:`~django.contrib.sitemaps.GenericSitemap`
  171. constructor to specify these attributes for all URLs.
  172. Example
  173. -------
  174. Here's an example of a :doc:`URLconf </topics/http/urls>` using both::
  175. from django.conf.urls.defaults import *
  176. from django.contrib.sitemaps import FlatPageSitemap, GenericSitemap
  177. from mysite.blog.models import Entry
  178. info_dict = {
  179. 'queryset': Entry.objects.all(),
  180. 'date_field': 'pub_date',
  181. }
  182. sitemaps = {
  183. 'flatpages': FlatPageSitemap,
  184. 'blog': GenericSitemap(info_dict, priority=0.6),
  185. }
  186. urlpatterns = patterns('',
  187. # some generic view using info_dict
  188. # ...
  189. # the sitemap
  190. (r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps})
  191. )
  192. .. _URLconf: ../url_dispatch/
  193. Creating a sitemap index
  194. ========================
  195. The sitemap framework also has the ability to create a sitemap index that
  196. references individual sitemap files, one per each section defined in your
  197. :data:`sitemaps` dictionary. The only differences in usage are:
  198. * You use two views in your URLconf: :func:`django.contrib.sitemaps.views.index`
  199. and :func:`django.contrib.sitemaps.views.sitemap`.
  200. * The :func:`django.contrib.sitemaps.views.sitemap` view should take a
  201. :data:`section` keyword argument.
  202. Here's what the relevant URLconf lines would look like for the example above::
  203. (r'^sitemap\.xml$', 'django.contrib.sitemaps.views.index', {'sitemaps': sitemaps}),
  204. (r'^sitemap-(?P<section>.+)\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
  205. This will automatically generate a :file:`sitemap.xml` file that references both
  206. :file:`sitemap-flatpages.xml` and :file:`sitemap-blog.xml`. The
  207. :class:`~django.contrib.sitemaps.Sitemap` classes and the :data:`sitemaps` dict
  208. don't change at all.
  209. You should create an index file if one of your sitemaps has more than 50,000
  210. URLs. In this case, Django will automatically paginate the sitemap, and the
  211. index will reflect that.
  212. Pinging Google
  213. ==============
  214. You may want to "ping" Google when your sitemap changes, to let it know to
  215. reindex your site. The sitemaps framework provides a function to do just
  216. that: :func:`django.contrib.sitemaps.ping_google()`.
  217. .. function:: ping_google
  218. :func:`ping_google` takes an optional argument, :data:`sitemap_url`,
  219. which should be the absolute URL of your site's sitemap (e.g.,
  220. :file:`'/sitemap.xml'`). If this argument isn't provided,
  221. :func:`ping_google` will attempt to figure out your
  222. sitemap by performing a reverse looking in your URLconf.
  223. :func:`ping_google` raises the exception
  224. :exc:`django.contrib.sitemaps.SitemapNotFound` if it cannot determine your
  225. sitemap URL.
  226. .. admonition:: Register with Google first!
  227. The :func:`ping_google` command only works if you have registered your
  228. site with `Google Webmaster Tools`_.
  229. .. _`Google Webmaster Tools`: http://www.google.com/webmasters/tools/
  230. One useful way to call :func:`ping_google` is from a model's ``save()``
  231. method::
  232. from django.contrib.sitemaps import ping_google
  233. class Entry(models.Model):
  234. # ...
  235. def save(self, force_insert=False, force_update=False):
  236. super(Entry, self).save(force_insert, force_update)
  237. try:
  238. ping_google()
  239. except Exception:
  240. # Bare 'except' because we could get a variety
  241. # of HTTP-related exceptions.
  242. pass
  243. A more efficient solution, however, would be to call :func:`ping_google` from a
  244. cron script, or some other scheduled task. The function makes an HTTP request
  245. to Google's servers, so you may not want to introduce that network overhead
  246. each time you call ``save()``.
  247. Pinging Google via `manage.py`
  248. ------------------------------
  249. .. versionadded:: 1.0
  250. Once the sitemaps application is added to your project, you may also
  251. ping the Google server's through the command line manage.py interface::
  252. python manage.py ping_google [/sitemap.xml]