---
title: "Kerangka peta situs"
version: 1.11
locale: id
source: https://docs.djangoproject.com/id/1.11/ref/contrib/sitemaps/
canonical: https://djangodocs.dev/id/1.11/ref/contrib/sitemaps/
---
# Kerangka peta situs

Django datang dengan kerangka kerja membangkitkan-peta situs tingkat-tinggi yang membuat pembuatan berkas-berkas XML [sitemap](https://www.sitemaps.org/) mudah.

## Ikhtisar

A sitemap is an XML file on your website that tells search-engine indexers how
frequently your pages change and how "important" certain pages are in relation
to other pages on your site. This information helps search engines index your
site.

Kerangka kerja peta situs Django mengotomatiskan pembuatan dari berkas XML ini dengan membiarkan anda menyatakan informasi ini di kode Python.

It works much like Django's [syndication framework](/id/1.11/ref/contrib/syndication/). To create a sitemap, just write a
[`Sitemap`](#django.contrib.sitemaps.Sitemap) class and point to it in your
[URLconf](/id/1.11/topics/http/urls/).

## Pemasangan

Untuk memasang aplikasi peta situs, ikuti langkah-langkah ini:

1. Tambah `'django.contrib.sitemaps'` ke pengaturan [`INSTALLED_APPS`](/id/1.11/ref/settings/#std-setting-INSTALLED_APPS) anda.
2. Make sure your [`TEMPLATES`](/id/1.11/ref/settings/#std-setting-TEMPLATES) setting contains a `DjangoTemplates`
   backend whose `APP_DIRS` options is set to `True`. It's in there by
   default, so you'll only need to change this if you've changed that setting.
3. Pastikan anda telah memasang [`sites framework`](/id/1.11/ref/contrib/sites/#module-django.contrib.sites).

(Note: The sitemap application doesn't install any database tables. The only
reason it needs to go into [`INSTALLED_APPS`](/id/1.11/ref/settings/#std-setting-INSTALLED_APPS) is so that the
[`Loader()`](/id/1.11/ref/templates/api/#django.template.loaders.app_directories.Loader) template
loader can find the default templates.)

## Inisialisasi

#### `views.sitemap(request, sitemaps, section=None, template_name='sitemap.xml', content_type='application/xml')`

Untuk mengaktifkan pembangkitan peta situs pada situs Django anda, tambah baris ini ke [URLconf](/id/1.11/topics/http/urls/) anda:

```
from django.contrib.sitemaps.views import sitemap

url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
    name='django.contrib.sitemaps.views.sitemap')
```

Ini mengatakan Django membangun sebuah peta situs ketika seorang klien mengakses `/sitemap.xml`.

The name of the sitemap file is not important, but the location is. Search
engines will only index links in your sitemap for the current URL level and
below. For instance, if `sitemap.xml` lives in your root directory, it may
reference any URL in your site. However, if your sitemap lives at
`/content/sitemap.xml`, it may only reference URLs that begin with
`/content/`.

The sitemap view takes an extra, required argument: `{'sitemaps': sitemaps}`.
`sitemaps` should be a dictionary that maps a short section label (e.g.,
`blog` or `news`) to its [`Sitemap`](#django.contrib.sitemaps.Sitemap) class
(e.g., `BlogSitemap` or `NewsSitemap`). It may also map to an *instance* of
a [`Sitemap`](#django.contrib.sitemaps.Sitemap) class (e.g.,
`BlogSitemap(some_var)`).

## Kelas `Sitemap`

A [`Sitemap`](#django.contrib.sitemaps.Sitemap) class is a simple Python
class that represents a "section" of entries in your sitemap. For example,
one [`Sitemap`](#django.contrib.sitemaps.Sitemap) class could represent
all the entries of your Weblog, while another could represent all of the
events in your events calendar.

In the simplest case, all these sections get lumped together into one
`sitemap.xml`, but it's also possible to use the framework to generate a
sitemap index that references individual sitemap files, one per section. (See
[Creating a sitemap index](#creating-a-sitemap-index) below.)

Kelas-kelas [`Sitemap`](#django.contrib.sitemaps.Sitemap) harus mengsubkelaskan `django.contrib.sitemaps.Sitemap`. Mereka dapat tinggal dimana saja dalam basis kode anda.

## Sebuah contoh sederhana

Mari kita beranggapan anda mempunyai sebuah sistem blog, dengan sebuah model `Entry`, dan anda ingin peta situs anda menyertakan semua tautan ke masukan blog pribadi anda. Ini adalah bagaimana kelas petasitus anda mungkin terlihat:

```
from django.contrib.sitemaps import Sitemap
from blog.models import Entry

class BlogSitemap(Sitemap):
    changefreq = "never"
    priority = 0.5

    def items(self):
        return Entry.objects.filter(is_draft=False)

    def lastmod(self, obj):
        return obj.pub_date
```

Catatan:

- [`changefreq`](#django.contrib.sitemaps.Sitemap.changefreq) and [`priority`](#django.contrib.sitemaps.Sitemap.priority) are class
  attributes corresponding to `<changefreq>` and `<priority>` elements,
  respectively. They can be made callable as functions, as
  [`lastmod`](#django.contrib.sitemaps.Sitemap.lastmod) was in the example.
- [`items()`](#django.contrib.sitemaps.Sitemap.items) is simply a method that returns a list of
  objects. The objects returned will get passed to any callable methods
  corresponding to a sitemap property ([`location`](#django.contrib.sitemaps.Sitemap.location),
  [`lastmod`](#django.contrib.sitemaps.Sitemap.lastmod), [`changefreq`](#django.contrib.sitemaps.Sitemap.changefreq), and
  [`priority`](#django.contrib.sitemaps.Sitemap.priority)).
- [`lastmod`](#django.contrib.sitemaps.Sitemap.lastmod) harus mengembalikan sebuah [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime).
- There is no [`location`](#django.contrib.sitemaps.Sitemap.location) method in this example, but you
  can provide it in order to specify the URL for your object. By default,
  [`location()`](#django.contrib.sitemaps.Sitemap.location) calls `get_absolute_url()` on each object
  and returns the result.

## Acuan kelas `Sitemap`

#### `class Sitemap`

Sebuah kelas `Sitemap` dapat menentukan metode/atribut berikut:

#### `items`

**Required.** A method that returns a list of objects. The framework
doesn't care what *type* of objects they are; all that matters is that
these objects get passed to the [`location()`](#django.contrib.sitemaps.Sitemap.location),
[`lastmod()`](#django.contrib.sitemaps.Sitemap.lastmod), [`changefreq()`](#django.contrib.sitemaps.Sitemap.changefreq) and
[`priority()`](#django.contrib.sitemaps.Sitemap.priority) methods.

#### `location`

**Pilihan.** Antara sebuah metode atau atribut.

Jika itu adalah sebuah metode, itu harus mengembalikan jalur mutlak untuk obyek yang diberikan sebagai dikembalikan oleh [`items()`](#django.contrib.sitemaps.Sitemap.items).

Jika itu adalah sebuah atribut, nilainya harus berupa string mewakili sebuah jalur mutlak untuk digunakan *setiap* obyek dikembalikan oleh [`items()`](#django.contrib.sitemaps.Sitemap.items).

Di kedua kasus, "absolute path" berarti sebuah URL yang tidak menyertakan protokol atau ranah. Contoh:

- Baik: `'/foo/bar/'`
- Buruk: `'example.com/foo/bar/'`
- Buruk: `'https://example.com/foo/bar/'`

Jika [`location`](#django.contrib.sitemaps.Sitemap.location) tidak disediakan, kerangka kerja akan memanggil metode `get_absolute_url()` pada setiap obyek sebagai dikembalikan oleh [`items()`](#django.contrib.sitemaps.Sitemap.items).

Untuk menentukan sebuah protokol selain dari `'http'`, gunakan [`protocol`](#django.contrib.sitemaps.Sitemap.protocol).

#### `lastmod`

**Pilihan.** Antara sebuah metode atau atribut.

Jika itu adalah sebuah metode, itu harus mengambil satu argumen - sebuah obyek seperti dikembalikan oleh [`items()`](#django.contrib.sitemaps.Sitemap.items) -- dan mengembalikan tanggal/waktu dirubah-terakhir obyek itu seperti [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime).

If it's an attribute, its value should be a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime)
representing the last-modified date/time for *every* object returned by
[`items()`](#django.contrib.sitemaps.Sitemap.items).

If all items in a sitemap have a [`lastmod`](#django.contrib.sitemaps.Sitemap.lastmod), the sitemap
generated by [`views.sitemap()`](#django.contrib.sitemaps.views.sitemap) will have a `Last-Modified`
header equal to the latest `lastmod`. You can activate the
[`ConditionalGetMiddleware`](/id/1.11/ref/middleware/#django.middleware.http.ConditionalGetMiddleware) to make
Django respond appropriately to requests with an `If-Modified-Since`
header which will prevent sending the sitemap if it hasn't changed.

#### `changefreq`

**Pilihan.** Antara sebuah metode atau atribut.

If it's a method, it should take one argument -- an object as returned
by [`items()`](#django.contrib.sitemaps.Sitemap.items) -- and return that object's change
frequency as a string.

If it's an attribute, its value should be a string representing the
change frequency of *every* object returned by [`items()`](#django.contrib.sitemaps.Sitemap.items).

Possible values for [`changefreq`](#django.contrib.sitemaps.Sitemap.changefreq), whether you use a
method or attribute, are:

- `'always'`
- `'hourly'`
- `'daily'`
- `'daily'`
- `'daily'`
- `'yearly'`
- `'never'`

#### `priority`

**Pilihan.** Antara sebuah metode atau atribut.

Jika itu adalah sebuah metode, itu harus mengambil satu argumen - sebuah obyek seperti dikembalikan oleh [`items()`](#django.contrib.sitemaps.Sitemap.items) -- dan mengembalikan prioritas obyek itu antara string atau float.

Jika itu adalah sebuah atribut, nilainya harus antra string atau float mewakili prioritas dari *setiap* obyek dikembalikan oleh [`items()`](#django.contrib.sitemaps.Sitemap.items).

Contoh nilai-nilai untuk [`priority`](#django.contrib.sitemaps.Sitemap.priority): `0.4`, `1.0`. Prioritas awalan dari sebuah halaman adalah `0.5`. Lihat [sitemaps.org documentation](https://www.sitemaps.org/protocol.html#prioritydef) untuk beberapa.

#### `protocol`

**Pilihan.**

Atribut ini menentukan protokol (`'http'` atau `'https'`) dari URL di peta situs. Jika itu tidak disetel, protokol dengan peta situs mana yang telah diminta digunakan. Jika peta situs dibangun diluar konteks dari permintaan, awalan adalah `'http'`.

#### `limit`

**Pilihan.**

This attribute defines the maximum number of URLs included on each page
of the sitemap. Its value should not exceed the default value of
`50000`, which is the upper limit allowed in the [Sitemaps protocol](https://www.sitemaps.org/protocol.html#index).

#### `i18n`

**Pilihan.**

Sebuah atribut boolean yang menentukan jika URL dari peta situs ini harus dibangkitkan menggunakan semua [`LANGUAGES`](/id/1.11/ref/settings/#std-setting-LANGUAGES) anda. Awalan adalah `False`.

## Jalan pintas

Kerangka kerja peta situs menyediakan sebuah kelas mudah untuk kasus tertentu:

#### `class GenericSitemap`

The [`django.contrib.sitemaps.GenericSitemap`](#django.contrib.sitemaps.GenericSitemap) class allows you to
create a sitemap by passing it a dictionary which has to contain at least
a `queryset` entry. This queryset will be used to generate the items
of the sitemap. It may also have a `date_field` entry that
specifies a date field for objects retrieved from the `queryset`.
This will be used for the [`lastmod`](#django.contrib.sitemaps.Sitemap.lastmod) attribute in the
generated sitemap. You may also pass [`priority`](#django.contrib.sitemaps.Sitemap.priority) and
[`changefreq`](#django.contrib.sitemaps.Sitemap.changefreq) keyword arguments to the
[`GenericSitemap`](#django.contrib.sitemaps.GenericSitemap)  constructor to specify
these attributes for all URLs.

### Contoh

Ini adalah contoh dari [URLconf](/id/1.11/topics/http/urls/) menggunakan [`GenericSitemap`](#django.contrib.sitemaps.GenericSitemap):

```
from django.conf.urls import url
from django.contrib.sitemaps import GenericSitemap
from django.contrib.sitemaps.views import sitemap
from blog.models import Entry

info_dict = {
    'queryset': Entry.objects.all(),
    'date_field': 'pub_date',
}

urlpatterns = [
    # some generic view using info_dict
    # ...

    # the sitemap
    url(r'^sitemap\.xml$', sitemap,
        {'sitemaps': {'blog': GenericSitemap(info_dict, priority=0.6)}},
        name='django.contrib.sitemaps.views.sitemap'),
]
```

## Peta situs untuk tampilan tetap

Often you want the search engine crawlers to index views which are neither
object detail pages nor flatpages. The solution is to explicitly list URL
names for these views in `items` and call [`reverse()`](/id/1.11/ref/urlresolvers/#django.urls.reverse) in
the `location` method of the sitemap. For example:

```
# sitemaps.py
from django.contrib import sitemaps
from django.urls import reverse

class StaticViewSitemap(sitemaps.Sitemap):
    priority = 0.5
    changefreq = 'daily'

    def items(self):
        return ['main', 'about', 'license']

    def location(self, item):
        return reverse(item)

# urls.py
from django.conf.urls import url
from django.contrib.sitemaps.views import sitemap

from .sitemaps import StaticViewSitemap
from . import views

sitemaps = {
    'static': StaticViewSitemap,
}

urlpatterns = [
    url(r'^$', views.main, name='main'),
    url(r'^about/$', views.about, name='about'),
    url(r'^license/$', views.license, name='license'),
    # ...
    url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
        name='django.contrib.sitemaps.views.sitemap')
]
```

## Membuat indeks peta situs

#### `views.index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap')`

The sitemap framework also has the ability to create a sitemap index that
references individual sitemap files, one per each section defined in your
`sitemaps` dictionary. The only differences in usage are:

- You use two views in your URLconf: [`django.contrib.sitemaps.views.index()`](#django.contrib.sitemaps.views.index)
  and [`django.contrib.sitemaps.views.sitemap()`](#django.contrib.sitemaps.views.sitemap).
- The [`django.contrib.sitemaps.views.sitemap()`](#django.contrib.sitemaps.views.sitemap) view should take a
  `section` keyword argument.

Here's what the relevant URLconf lines would look like for the example above:

```
from django.contrib.sitemaps import views

urlpatterns = [
    url(r'^sitemap\.xml$', views.index, {'sitemaps': sitemaps}),
    url(r'^sitemap-(?P<section>.+)\.xml$', views.sitemap, {'sitemaps': sitemaps},
        name='django.contrib.sitemaps.views.sitemap'),
]
```

This will automatically generate a `sitemap.xml` file that references
both `sitemap-flatpages.xml` and `sitemap-blog.xml`. The
[`Sitemap`](#django.contrib.sitemaps.Sitemap) classes and the `sitemaps`
dict don't change at all.

You should create an index file if one of your sitemaps has more than 50,000
URLs. In this case, Django will automatically paginate the sitemap, and the
index will reflect that.

If you're not using the vanilla sitemap view -- for example, if it's wrapped
with a caching decorator -- you must name your sitemap view and pass
`sitemap_url_name` to the index view:

```
from django.contrib.sitemaps import views as sitemaps_views
from django.views.decorators.cache import cache_page

urlpatterns = [
    url(r'^sitemap\.xml$',
        cache_page(86400)(sitemaps_views.index),
        {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),
    url(r'^sitemap-(?P<section>.+)\.xml$',
        cache_page(86400)(sitemaps_views.sitemap),
        {'sitemaps': sitemaps}, name='sitemaps'),
]
```

## Template customization

If you wish to use a different template for each sitemap or sitemap index
available on your site, you may specify it by passing a `template_name`
parameter to the `sitemap` and `index` views via the URLconf:

```
from django.contrib.sitemaps import views

urlpatterns = [
    url(r'^custom-sitemap\.xml$', views.index, {
        'sitemaps': sitemaps,
        'template_name': 'custom_sitemap.html'
    }),
    url(r'^custom-sitemap-(?P<section>.+)\.xml$', views.sitemap, {
        'sitemaps': sitemaps,
        'template_name': 'custom_sitemap.html'
    }, name='django.contrib.sitemaps.views.sitemap'),
]
```

Tampilan ini mengembalikan instance [`TemplateResponse`](/id/1.11/ref/template-response/#django.template.response.TemplateResponse) yang mengizinkan anda dengan mudah menyesuaikan data tanggapan sebelum membangun. Untuk rincian lebih, lihat [TemplateResponse documentation](/id/1.11/ref/template-response/).

### Context variables

When customizing the templates for the
[`index()`](#django.contrib.sitemaps.views.index) and
[`sitemap()`](#django.contrib.sitemaps.views.sitemap) views, you can rely on the
following context variables.

### Indeks

The variable `sitemaps` is a list of absolute URLs to each of the sitemaps.

### Sitemap

The variable `urlset` is a list of URLs that should appear in the
sitemap. Each URL exposes attributes as defined in the
[`Sitemap`](#django.contrib.sitemaps.Sitemap) class:

- `changefreq`
- `item`
- `lastmod`
- `tempat`
- `prioritas`

The `item` attribute has been added for each URL to allow more flexible
customization of the templates, such as [Google news sitemaps](https://support.google.com/news/publisher/answer/74288?hl=en). Assuming
Sitemap's [`items()`](#django.contrib.sitemaps.Sitemap.items) would return a list of items with
`publication_data` and a `tags` field something like this would
generate a Google News compatible sitemap:

```xml+django
<?xml version="1.0" encoding="UTF-8"?>
<urlset
  xmlns="https://www.sitemaps.org/schemas/sitemap/0.9"
  xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
{% spaceless %}
{% for url in urlset %}
  <url>
    <loc>{{ url.location }}</loc>
    {% if url.lastmod %}<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>{% endif %}
    {% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %}
    {% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %}
    <news:news>
      {% if url.item.publication_date %}<news:publication_date>{{ url.item.publication_date|date:"Y-m-d" }}</news:publication_date>{% endif %}
      {% if url.item.tags %}<news:keywords>{{ url.item.tags }}</news:keywords>{% endif %}
    </news:news>
   </url>
{% endfor %}
{% endspaceless %}
</urlset>
```

## Pinging Google

You may want to "ping" Google when your sitemap changes, to let it know to
reindex your site. The sitemaps framework provides a function to do just
that: [`django.contrib.sitemaps.ping_google()`](#django.contrib.sitemaps.ping_google).

#### `ping_google()`

[`ping_google()`](#django.contrib.sitemaps.ping_google) takes an optional argument, `sitemap_url`,
which should be the absolute path to your site's sitemap (e.g.,
`'/sitemap.xml'`). If this argument isn't provided,
[`ping_google()`](#django.contrib.sitemaps.ping_google) will attempt to figure out your
sitemap by performing a reverse looking in your URLconf.

[`ping_google()`](#django.contrib.sitemaps.ping_google) raises the exception
`django.contrib.sitemaps.SitemapNotFound` if it cannot determine your
sitemap URL.

> **Register with Google first!**
>
> The [`ping_google()`](#django.contrib.sitemaps.ping_google) command only works if you have registered your
> site with [Google Webmaster Tools](https://www.google.com/webmasters/tools/).

One useful way to call [`ping_google()`](#django.contrib.sitemaps.ping_google) is from a model's `save()`
method:

```
from django.contrib.sitemaps import ping_google

class Entry(models.Model):
    # ...
    def save(self, force_insert=False, force_update=False):
        super(Entry, self).save(force_insert, force_update)
        try:
            ping_google()
        except Exception:
            # Bare 'except' because we could get a variety
            # of HTTP-related exceptions.
            pass
```

A more efficient solution, however, would be to call [`ping_google()`](#django.contrib.sitemaps.ping_google) from a
cron script, or some other scheduled task. The function makes an HTTP request
to Google's servers, so you may not want to introduce that network overhead
each time you call `save()`.

### Pinging Google via `manage.py`

#### `django-admin ping_google [sitemap_url]`

Once the sitemaps application is added to your project, you may also
ping Google using the `ping_google` management command:

```
python manage.py ping_google [/sitemap.xml]
```
