sitemaps.txt 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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 to create sitemap_
  7. XML files.
  8. .. _sitemap: https://www.sitemaps.org/
  9. Overview
  10. ========
  11. A sitemap is an XML file on your website 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, 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. #. Add ``'django.contrib.sitemaps'`` to your :setting:`INSTALLED_APPS` setting.
  25. #. Make sure your :setting:`TEMPLATES` setting contains a ``DjangoTemplates``
  26. backend whose ``APP_DIRS`` options is set to ``True``. It's in there by
  27. default, so you'll only need to change this if you've changed that setting.
  28. #. Make sure you've installed the :mod:`sites framework<django.contrib.sites>`.
  29. (Note: The sitemap application doesn't install any database tables. The only
  30. reason it needs to go into :setting:`INSTALLED_APPS` is so that the
  31. :func:`~django.template.loaders.app_directories.Loader` template
  32. loader can find the default templates.)
  33. Initialization
  34. ==============
  35. .. function:: views.sitemap(request, sitemaps, section=None, template_name='sitemap.xml', content_type='application/xml')
  36. To activate sitemap generation on your Django site, add this line to your
  37. :doc:`URLconf </topics/http/urls>`::
  38. from django.contrib.sitemaps.views import sitemap
  39. path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
  40. name='django.contrib.sitemaps.views.sitemap')
  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 Python class that
  57. represents a "section" of entries in your sitemap. For example, one
  58. :class:`~django.contrib.sitemaps.Sitemap` class could represent all the entries
  59. of your blog, while another could represent all of the events in your events
  60. 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. An 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 a method that returns a :term:`sequence` or
  87. ``QuerySet`` of objects. The objects returned will get passed to any callable
  88. methods 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 :class:`~datetime.datetime`.
  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 :term:`sequence` or ``QuerySet``
  102. of objects. The framework doesn't care what *type* of objects they are;
  103. all that matters is that these objects get passed to the
  104. :attr:`~Sitemap.location()`, :attr:`~Sitemap.lastmod()`,
  105. :attr:`~Sitemap.changefreq()` and :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: ``'/foo/bar/'``
  116. * Bad: ``'example.com/foo/bar/'``
  117. * Bad: ``'https://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
  126. by :attr:`~Sitemap.items()` -- and return that object's last-modified
  127. date/time as a :class:`~datetime.datetime`.
  128. If it's an attribute, its value should be a :class:`~datetime.datetime`
  129. representing the last-modified date/time for *every* object returned by
  130. :attr:`~Sitemap.items()`.
  131. If all items in a sitemap have a :attr:`~Sitemap.lastmod`, the sitemap
  132. generated by :func:`views.sitemap` will have a ``Last-Modified``
  133. header equal to the latest ``lastmod``. You can activate the
  134. :class:`~django.middleware.http.ConditionalGetMiddleware` to make
  135. Django respond appropriately to requests with an ``If-Modified-Since``
  136. header which will prevent sending the sitemap if it hasn't changed.
  137. .. attribute:: Sitemap.paginator
  138. **Optional.**
  139. This property returns a :class:`~django.core.paginator.Paginator` for
  140. :attr:`~Sitemap.items()`. If you generate sitemaps in a batch you may
  141. want to override this as a cached property in order to avoid multiple
  142. ``items()`` calls.
  143. .. attribute:: Sitemap.changefreq
  144. **Optional.** Either a method or attribute.
  145. If it's a method, it should take one argument -- an object as returned
  146. by :attr:`~Sitemap.items()` -- and return that object's change
  147. frequency as a string.
  148. If it's an attribute, its value should be a string representing the
  149. change frequency of *every* object returned by :attr:`~Sitemap.items()`.
  150. Possible values for :attr:`~Sitemap.changefreq`, whether you use a
  151. method or attribute, are:
  152. * ``'always'``
  153. * ``'hourly'``
  154. * ``'daily'``
  155. * ``'weekly'``
  156. * ``'monthly'``
  157. * ``'yearly'``
  158. * ``'never'``
  159. .. attribute:: Sitemap.priority
  160. **Optional.** Either a method or attribute.
  161. If it's a method, it should take one argument -- an object as returned
  162. by :attr:`~Sitemap.items()` -- and return that object's priority as
  163. either a string or float.
  164. If it's an attribute, its value should be either a string or float
  165. representing the priority of *every* object returned by
  166. :attr:`~Sitemap.items()`.
  167. Example values for :attr:`~Sitemap.priority`: ``0.4``, ``1.0``. The
  168. default priority of a page is ``0.5``. See the `sitemaps.org
  169. documentation`_ for more.
  170. .. _sitemaps.org documentation: https://www.sitemaps.org/protocol.html#prioritydef
  171. .. attribute:: Sitemap.protocol
  172. **Optional.**
  173. This attribute defines the protocol (``'http'`` or ``'https'``) of the
  174. URLs in the sitemap. If it isn't set, the protocol with which the
  175. sitemap was requested is used. If the sitemap is built outside the
  176. context of a request, the default is ``'https'``.
  177. .. versionchanged:: 5.0
  178. In older versions, the default protocol for sitemaps built outside
  179. the context of a request was ``'http'``.
  180. .. attribute:: Sitemap.limit
  181. **Optional.**
  182. This attribute defines the maximum number of URLs included on each page
  183. of the sitemap. Its value should not exceed the default value of
  184. ``50000``, which is the upper limit allowed in the `Sitemaps protocol
  185. <https://www.sitemaps.org/protocol.html#index>`_.
  186. .. attribute:: Sitemap.i18n
  187. **Optional.**
  188. A boolean attribute that defines if the URLs of this sitemap should
  189. be generated using all of your :setting:`LANGUAGES`. The default is
  190. ``False``.
  191. .. attribute:: Sitemap.languages
  192. **Optional.**
  193. A :term:`sequence` of :term:`language codes<language code>` to use for
  194. generating alternate links when :attr:`~Sitemap.i18n` is enabled.
  195. Defaults to :setting:`LANGUAGES`.
  196. .. attribute:: Sitemap.alternates
  197. **Optional.**
  198. A boolean attribute. When used in conjunction with
  199. :attr:`~Sitemap.i18n` generated URLs will each have a list of alternate
  200. links pointing to other language versions using the `hreflang
  201. attribute`_. The default is ``False``.
  202. .. _hreflang attribute: https://developers.google.com/search/docs/advanced/crawling/localized-versions
  203. .. attribute:: Sitemap.x_default
  204. **Optional.**
  205. A boolean attribute. When ``True`` the alternate links generated by
  206. :attr:`~Sitemap.alternates` will contain a ``hreflang="x-default"``
  207. fallback entry with a value of :setting:`LANGUAGE_CODE`. The default is
  208. ``False``.
  209. .. method:: Sitemap.get_latest_lastmod()
  210. **Optional.** A method that returns the latest value returned by
  211. :attr:`~Sitemap.lastmod`. This function is used to add the ``lastmod``
  212. attribute to :ref:`Sitemap index context
  213. variables<sitemap-index-context-variables>`.
  214. By default :meth:`~Sitemap.get_latest_lastmod` returns:
  215. * If :attr:`~Sitemap.lastmod` is an attribute:
  216. :attr:`~Sitemap.lastmod`.
  217. * If :attr:`~Sitemap.lastmod` is a method:
  218. The latest ``lastmod`` returned by calling the method with all
  219. items returned by :meth:`Sitemap.items`.
  220. .. method:: Sitemap.get_languages_for_item(item, lang_code)
  221. .. versionadded:: 4.2
  222. **Optional.** A method that returns the sequence of language codes for
  223. which the item is displayed. By default
  224. :meth:`~Sitemap.get_languages_for_item` returns
  225. :attr:`~Sitemap.languages`.
  226. Shortcuts
  227. =========
  228. The sitemap framework provides a convenience class for a common case:
  229. .. class:: GenericSitemap(info_dict, priority=None, changefreq=None, protocol=None)
  230. The :class:`django.contrib.sitemaps.GenericSitemap` class allows you to
  231. create a sitemap by passing it a dictionary which has to contain at least
  232. a ``queryset`` entry. This queryset will be used to generate the items
  233. of the sitemap. It may also have a ``date_field`` entry that
  234. specifies a date field for objects retrieved from the ``queryset``.
  235. This will be used for the :attr:`~Sitemap.lastmod` attribute and
  236. :meth:`~Sitemap.get_latest_lastmod` methods in the in the
  237. generated sitemap.
  238. The :attr:`~Sitemap.priority`, :attr:`~Sitemap.changefreq`,
  239. and :attr:`~Sitemap.protocol` keyword arguments allow specifying these
  240. attributes for all URLs.
  241. Example
  242. -------
  243. Here's an example of a :doc:`URLconf </topics/http/urls>` using
  244. :class:`GenericSitemap`::
  245. from django.contrib.sitemaps import GenericSitemap
  246. from django.contrib.sitemaps.views import sitemap
  247. from django.urls import path
  248. from blog.models import Entry
  249. info_dict = {
  250. 'queryset': Entry.objects.all(),
  251. 'date_field': 'pub_date',
  252. }
  253. urlpatterns = [
  254. # some generic view using info_dict
  255. # ...
  256. # the sitemap
  257. path('sitemap.xml', sitemap,
  258. {'sitemaps': {'blog': GenericSitemap(info_dict, priority=0.6)}},
  259. name='django.contrib.sitemaps.views.sitemap'),
  260. ]
  261. .. _URLconf: ../url_dispatch/
  262. Sitemap for static views
  263. ========================
  264. Often you want the search engine crawlers to index views which are neither
  265. object detail pages nor flatpages. The solution is to explicitly list URL
  266. names for these views in ``items`` and call :func:`~django.urls.reverse` in
  267. the ``location`` method of the sitemap. For example::
  268. # sitemaps.py
  269. from django.contrib import sitemaps
  270. from django.urls import reverse
  271. class StaticViewSitemap(sitemaps.Sitemap):
  272. priority = 0.5
  273. changefreq = 'daily'
  274. def items(self):
  275. return ['main', 'about', 'license']
  276. def location(self, item):
  277. return reverse(item)
  278. # urls.py
  279. from django.contrib.sitemaps.views import sitemap
  280. from django.urls import path
  281. from .sitemaps import StaticViewSitemap
  282. from . import views
  283. sitemaps = {
  284. 'static': StaticViewSitemap,
  285. }
  286. urlpatterns = [
  287. path('', views.main, name='main'),
  288. path('about/', views.about, name='about'),
  289. path('license/', views.license, name='license'),
  290. # ...
  291. path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
  292. name='django.contrib.sitemaps.views.sitemap')
  293. ]
  294. Creating a sitemap index
  295. ========================
  296. .. function:: views.index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap')
  297. The sitemap framework also has the ability to create a sitemap index that
  298. references individual sitemap files, one per each section defined in your
  299. ``sitemaps`` dictionary. The only differences in usage are:
  300. * You use two views in your URLconf: :func:`django.contrib.sitemaps.views.index`
  301. and :func:`django.contrib.sitemaps.views.sitemap`.
  302. * The :func:`django.contrib.sitemaps.views.sitemap` view should take a
  303. ``section`` keyword argument.
  304. Here's what the relevant URLconf lines would look like for the example above::
  305. from django.contrib.sitemaps import views
  306. urlpatterns = [
  307. path('sitemap.xml', views.index, {'sitemaps': sitemaps},
  308. name='django.contrib.sitemaps.views.index'),
  309. path('sitemap-<section>.xml', views.sitemap, {'sitemaps': sitemaps},
  310. name='django.contrib.sitemaps.views.sitemap'),
  311. ]
  312. This will automatically generate a :file:`sitemap.xml` file that references
  313. both :file:`sitemap-flatpages.xml` and :file:`sitemap-blog.xml`. The
  314. :class:`~django.contrib.sitemaps.Sitemap` classes and the ``sitemaps``
  315. dict don't change at all.
  316. If all sitemaps have a ``lastmod`` returned by
  317. :meth:`Sitemap.get_latest_lastmod` the sitemap index will have a
  318. ``Last-Modified`` header equal to the latest ``lastmod``.
  319. You should create an index file if one of your sitemaps has more than 50,000
  320. URLs. In this case, Django will automatically paginate the sitemap, and the
  321. index will reflect that.
  322. If you're not using the vanilla sitemap view -- for example, if it's wrapped
  323. with a caching decorator -- you must name your sitemap view and pass
  324. ``sitemap_url_name`` to the index view::
  325. from django.contrib.sitemaps import views as sitemaps_views
  326. from django.views.decorators.cache import cache_page
  327. urlpatterns = [
  328. path('sitemap.xml',
  329. cache_page(86400)(sitemaps_views.index),
  330. {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),
  331. path('sitemap-<section>.xml',
  332. cache_page(86400)(sitemaps_views.sitemap),
  333. {'sitemaps': sitemaps}, name='sitemaps'),
  334. ]
  335. Template customization
  336. ======================
  337. If you wish to use a different template for each sitemap or sitemap index
  338. available on your site, you may specify it by passing a ``template_name``
  339. parameter to the ``sitemap`` and ``index`` views via the URLconf::
  340. from django.contrib.sitemaps import views
  341. urlpatterns = [
  342. path('custom-sitemap.xml', views.index, {
  343. 'sitemaps': sitemaps,
  344. 'template_name': 'custom_sitemap.html'
  345. }, name='django.contrib.sitemaps.views.index'),
  346. path('custom-sitemap-<section>.xml', views.sitemap, {
  347. 'sitemaps': sitemaps,
  348. 'template_name': 'custom_sitemap.html'
  349. }, name='django.contrib.sitemaps.views.sitemap'),
  350. ]
  351. These views return :class:`~django.template.response.TemplateResponse`
  352. instances which allow you to easily customize the response data before
  353. rendering. For more details, see the :doc:`TemplateResponse documentation
  354. </ref/template-response>`.
  355. Context variables
  356. -----------------
  357. When customizing the templates for the
  358. :func:`~django.contrib.sitemaps.views.index` and
  359. :func:`~django.contrib.sitemaps.views.sitemap` views, you can rely on the
  360. following context variables.
  361. .. _sitemap-index-context-variables:
  362. Index
  363. -----
  364. The variable ``sitemaps`` is a list of objects containing the ``location`` and
  365. ``lastmod`` attribute for each of the sitemaps. Each URL exposes the following
  366. attributes:
  367. - ``location``: The location (url & page) of the sitemap.
  368. - ``lastmod``: Populated by the :meth:`~Sitemap.get_latest_lastmod`
  369. method for each sitemap.
  370. Sitemap
  371. -------
  372. The variable ``urlset`` is a list of URLs that should appear in the
  373. sitemap. Each URL exposes attributes as defined in the
  374. :class:`~django.contrib.sitemaps.Sitemap` class:
  375. - ``alternates``
  376. - ``changefreq``
  377. - ``item``
  378. - ``lastmod``
  379. - ``location``
  380. - ``priority``
  381. The ``alternates`` attribute is available when :attr:`~Sitemap.i18n` and
  382. :attr:`~Sitemap.alternates` are enabled. It is a list of other language
  383. versions, including the optional :attr:`~Sitemap.x_default` fallback, for each
  384. URL. Each alternate is a dictionary with ``location`` and ``lang_code`` keys.
  385. The ``item`` attribute has been added for each URL to allow more flexible
  386. customization of the templates, such as `Google news sitemaps`_. Assuming
  387. Sitemap's :attr:`~Sitemap.items()` would return a list of items with
  388. ``publication_data`` and a ``tags`` field something like this would
  389. generate a Google News compatible sitemap:
  390. .. code-block:: xml+django
  391. <?xml version="1.0" encoding="UTF-8"?>
  392. <urlset
  393. xmlns="https://www.sitemaps.org/schemas/sitemap/0.9"
  394. xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
  395. {% spaceless %}
  396. {% for url in urlset %}
  397. <url>
  398. <loc>{{ url.location }}</loc>
  399. {% if url.lastmod %}<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>{% endif %}
  400. {% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %}
  401. {% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %}
  402. <news:news>
  403. {% if url.item.publication_date %}<news:publication_date>{{ url.item.publication_date|date:"Y-m-d" }}</news:publication_date>{% endif %}
  404. {% if url.item.tags %}<news:keywords>{{ url.item.tags }}</news:keywords>{% endif %}
  405. </news:news>
  406. </url>
  407. {% endfor %}
  408. {% endspaceless %}
  409. </urlset>
  410. .. _`Google news sitemaps`: https://support.google.com/news/publisher-center/answer/9606710
  411. Pinging Google
  412. ==============
  413. You may want to "ping" Google when your sitemap changes, to let it know to
  414. reindex your site. The sitemaps framework provides a function to do just
  415. that: :func:`django.contrib.sitemaps.ping_google()`.
  416. .. function:: ping_google(sitemap_url=None, ping_url=PING_URL, sitemap_uses_https=True)
  417. ``ping_google`` takes these optional arguments:
  418. * ``sitemap_url`` - The absolute path to your site's sitemap (e.g.,
  419. :file:`'/sitemap.xml'`).
  420. If this argument isn't provided, ``ping_google`` will perform a reverse
  421. lookup in your URLconf, for URLs named
  422. ``'django.contrib.sitemaps.views.index'`` and then
  423. ``'django.contrib.sitemaps.views.sitemap'`` (without further arguments) to
  424. automatically determine the sitemap URL.
  425. * ``ping_url`` - Defaults to Google's Ping Tool:
  426. https://www.google.com/webmasters/tools/ping.
  427. * ``sitemap_uses_https`` - Set to ``False`` if your site uses ``http``
  428. rather than ``https``.
  429. :func:`ping_google` raises the exception
  430. ``django.contrib.sitemaps.SitemapNotFound`` if it cannot determine your
  431. sitemap URL.
  432. .. admonition:: Register with Google first!
  433. The :func:`ping_google` command only works if you have registered your
  434. site with `Google Search Console`_.
  435. .. _`Google Search Console`: https://search.google.com/search-console/welcome
  436. One useful way to call :func:`ping_google` is from a model's ``save()``
  437. method::
  438. from django.contrib.sitemaps import ping_google
  439. class Entry(models.Model):
  440. # ...
  441. def save(self, force_insert=False, force_update=False):
  442. super().save(force_insert, force_update)
  443. try:
  444. ping_google()
  445. except Exception:
  446. # Bare 'except' because we could get a variety
  447. # of HTTP-related exceptions.
  448. pass
  449. A more efficient solution, however, would be to call :func:`ping_google` from a
  450. cron script, or some other scheduled task. The function makes an HTTP request
  451. to Google's servers, so you may not want to introduce that network overhead
  452. each time you call ``save()``.
  453. Pinging Google via ``manage.py``
  454. --------------------------------
  455. .. django-admin:: ping_google [sitemap_url]
  456. Once the sitemaps application is added to your project, you may also
  457. ping Google using the ``ping_google`` management command::
  458. python manage.py ping_google [/sitemap.xml]
  459. .. django-admin-option:: --sitemap-uses-http
  460. Use this option if your sitemap uses ``http`` rather than ``https``.