PageRenderTime 31ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

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