Kerangka peta situs¶
Django comes with a high-level sitemap-generating framework to create sitemap XML files.
Ikhtisar¶
Sebuah peta situs adalah sebuah berkas file pada situs jaringan anda yang memberitahu pengindeks mesin-pencari seberapa sering halaman anda berubah dan seberapa "penting" halaman tertentu berada dalam hubungan ke halaman lain pada situs anda. Informasi ini membantu mesin pencari mengindeks situs anda.
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. To create a sitemap, write a
Sitemap class and point to it in your
URLconf.
Pemasangan¶
Untuk memasang aplikasi peta situs, ikuti langkah-langkah ini:
Tambah
'django.contrib.sitemaps'ke pengaturanINSTALLED_APPSanda.Pastikan pengaturan anda
TEMPLATESmengandung sebuah backendDjangoTemplatesyang pilihanAPP_DIRSdisetel menjadiTrue. Itu ada disana secara awalan, jadi anda hanya akan butuh merubah ini jika anda yelah merubah pengaturan itu.Pastikan anda telah memasang
sites framework.
(Catat: Aplikasi peta situs tidak memasang tabel-tabel basisdata apapun. Alasan satu-satunya itu butuh it needs untuk masuk INSTALLED_APPS adalah sehingga pemuat cetakan:func:~django.template.loaders.app_directories.Loader dapat menemukan cetakan-cetakan awalan.)
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 anda:
from django.contrib.sitemaps.views import sitemap
path(
"sitemap.xml",
sitemap,
{"sitemaps": sitemaps},
name="django.contrib.sitemaps.views.sitemap",
)
Ini mengatakan Django membangun sebuah peta situs ketika seorang klien mengakses /sitemap.xml.
Nama dari berkas peta situs adalah tidak penting, tetapi tempat penting. Mesin pencari hanya mengindeks tautan dalam peta situs anda untuk tingkat URL saat ini dan dibawah. Sebagai contoh, jika sitemap.xml tinggal dalam direktori akar anda, itu mungkin mengacu URL apapun dalam situs anda. Bagaimanapun, jika peta situs anda tinggal di /content/sitemap.xml, itu mungkin hanya mengacu URL yang dimulai dengan /content/.
Tampilan peta situs mengambil sebuah tambahan, argumen diwajibkan: {'sitemaps': sitemaps}. sitemaps harus berupa dictionary yang memetakan label bagian pendek (misalnya., blog atau news) ke kelas Sitemap nya (misalnya, BlogSitemap atau NewsSitemap). Ity mungkin juga memetakan ke sebuah instance dari kelas Sitemap (misalnya, BlogSitemap(some_var)).
Kelas Sitemap¶
A Sitemap class is a Python class that
represents a "section" of entries in your sitemap. For example, one
Sitemap class could represent all the entries
of your blog, while another could represent all of the events in your events
calendar.
Dalam kasus tersederhana, semua bagian-bagian ini semua bagian ini dapat lumpuh bersama-sama menjadi satu sitemap.xml, tetapi itu juga memungkinkan menggunakan kerangka kerja untuk membangkitkan indeks peta situs yang mengacu berkas-berkas peta situs masing-masing, satu per bagian. (Lihat Creating a sitemap index dibawah ini.)
Kelas-kelas Sitemap harus mengsubkelaskan django.contrib.sitemaps.Sitemap. Mereka dapat tinggal dimana saja dalam basis kode anda.
Sebuah contoh¶
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:
changefreqdanpriorityadalah atribut kelas berhubungan pada unsur<changefreq>dan<priority>, masing-masing. Mereka dapat dibuat callable sebagai fungsi, sepertilastmodcalam contoh ini.items()is a method that returns a sequence orQuerySetof objects. The objects returned will get passed to any callable methods corresponding to a sitemap property (location,lastmod,changefreq, andpriority).There is no
locationmethod in this example, but you can provide it in order to specify the URL for your object. By default,locationcallsget_absolute_url()on each object and returns the result.
Acuan kelas Sitemap¶
- class Sitemap[sumber]¶
Sebuah kelas
Sitemapdapat menentukan metode/atribut berikut:- items()[sumber]¶
Required. A method that returns a sequence or
QuerySetof objects. The framework doesn't care what type of objects they are; all that matters is that these objects get passed to thelocation,lastmod,changefreqandprioritymethods.
- location[sumber]¶
Pilihan. Antara sebuah metode atau atribut.
If it's a method, it should return the absolute path for a given object as returned by
items().If it's an attribute, its value should be a string representing an absolute path to use for every object returned by
items().Di kedua kasus, "absolute path" berarti sebuah URL yang tidak menyertakan protokol atau ranah. Contoh:
Good:
'/foo/bar/'Bad:
'example.com/foo/bar/'Buruk:
'https://example.com/foo/bar/'
If
locationisn't provided, the framework will call theget_absolute_url()method on each object as returned byitems.Untuk menentukan sebuah protokol selain dari
'http', gunakanprotocol.
- lastmod¶
Pilihan. Antara sebuah metode atau atribut.
If it's a method, it should take one argument -- an object as returned by
items()-- and return that object's last-modified date/time as adatetime.If it's an attribute, its value should be a
datetimerepresenting the last-modified date/time for every object returned byitems().Jika semua barang dalam peta situs memiliki
lastmod, peta situs dibangkitkan olehviews.sitemap()akan mempunyai kepalaLast-Modifiedsetara padalastmodterakhir. Anda dapat mengaktifkanConditionalGetMiddlewareuntuk membuat Django menjawab sesuai permintaan dengan sebuah kepalaIf-Modified-Sinceyang akan mencegah mengirim peta situs jika itu belum berubah.
- paginator[sumber]¶
Pilihan.
This property returns a
Paginatorforitems(). If you generate sitemaps in a batch you may want to override this as a cached property in order to avoid multipleitems()calls.
- changefreq¶
Pilihan. Antara sebuah metode atau atribut.
If it's a method, it should take one argument -- an object as returned by
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().Nilai memungkinkan untuk
changefreq, apakah anda menggunakan sebuah metode atau atribut, adalah:'always''hourly''daily''daily''daily''yearly''never'
- priority¶
Pilihan. Antara sebuah metode atau atribut.
If it's a method, it should take one argument -- an object as returned by
items()-- and return that object's priority as either a string or float.If it's an attribute, its value should be either a string or float representing the priority of every object returned by
items().Contoh nilai-nilai untuk
priority:0.4,1.0. Prioritas awalan dari sebuah halaman adalah0.5. Lihat sitemaps.org documentation untuk beberapa.
- protocol¶
Pilihan.
This attribute defines the protocol (
'http'or'https') of the URLs in the sitemap. If it isn't set, the protocol with which the sitemap was requested is used. If the sitemap is built outside the context of a request, the default is'https'.
- limit¶
Pilihan.
Atribut ini menentukan angka maksimal dari URL disertakan pada setiap halaman dari peta situs. Nilainya tidak harus melebihi nilai awalan dari
50000, yang merupakan batas teratas diijinkan dalam Sitemaps protocol.
- i18n¶
Pilihan.
Sebuah atribut boolean yang menentukan jika URL dari peta situs ini harus dibangkitkan menggunakan semua
LANGUAGESanda. Awalan adalahFalse.
- languages¶
Pilihan.
A sequence of language codes to use for generating alternate links when
i18nis enabled. Defaults toLANGUAGES.
- alternates¶
Pilihan.
A boolean attribute. When used in conjunction with
i18ngenerated URLs will each have a list of alternate links pointing to other language versions using the hreflang attribute. The default isFalse.
- x_default¶
Pilihan.
A boolean attribute. When
Truethe alternate links generated byalternateswill contain ahreflang="x-default"fallback entry with a value ofLANGUAGE_CODE. The default isFalse.
- get_latest_lastmod()[sumber]¶
Optional. A method that returns the latest value returned by
lastmod. This function is used to add thelastmodattribute to Sitemap index context variables.By default
get_latest_lastmod()returns:
- get_languages_for_item(item)[sumber]¶
Optional. A method that returns the sequence of language codes for which the item is displayed. By default
get_languages_for_item()returnslanguages.
Jalan pintas¶
Kerangka kerja peta situs menyediakan sebuah kelas mudah untuk kasus tertentu:
- class GenericSitemap(info_dict, priority=None, changefreq=None, protocol=None)[sumber]¶
The
django.contrib.sitemaps.GenericSitemapclass allows you to create a sitemap by passing it a dictionary which has to contain at least aquerysetentry. This queryset will be used to generate the items of the sitemap. It may also have adate_fieldentry that specifies a date field for objects retrieved from thequeryset. This will be used for thelastmodattribute andget_latest_lastmod()methods in the in the generated sitemap.Argumen kata kunci
priority,changefreq, danprotocolmengizinkan menentukan atribut-atribut ini untuk semua URL.
Contoh¶
Ini adalah contoh dari URLconf menggunakan GenericSitemap:
from django.contrib.sitemaps import GenericSitemap
from django.contrib.sitemaps.views import sitemap
from django.urls import path
from blog.models import Entry
info_dict = {
"queryset": Entry.objects.all(),
"date_field": "pub_date",
}
urlpatterns = [
# some generic view using info_dict
# ...
# the sitemap
path(
"sitemap.xml",
sitemap,
{"sitemaps": {"blog": GenericSitemap(info_dict, priority=0.6)}},
name="django.contrib.sitemaps.views.sitemap",
),
]
Peta situs untuk tampilan tetap¶
Sering anda ingin perayap mesin pencari untuk mengindeks tampilan-tampilan yang tidak juga halaman-halaman rinci obyek maupun halaman datar. Pemecahanannya adalah secara tersirat daftar nama-nama URL untuk tampilan-tampilan ini dalam items dan panggil reverse() dalam metode location dari peta situs. Sebagai contoh:
# 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.contrib.sitemaps.views import sitemap
from django.urls import path
from .sitemaps import StaticViewSitemap
from . import views
sitemaps = {
"static": StaticViewSitemap,
}
urlpatterns = [
path("", views.main, name="main"),
path("about/", views.about, name="about"),
path("license/", views.license, name="license"),
# ...
path(
"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')¶
Kerangka kerja peta situs juga memiliki kemampuan membuat sebuah indeks peta situs yang mengacu ke berkas-berkas peta situs masing-masing, satu per setiap bagian ditentukan dalam dictionary sitemaps anda. Perbedaan hanya dalam penggunaan adalah:
Anda dapat menggunakan dua tampilan dalam URLconf anda:
django.contrib.sitemaps.views.index()dandjango.contrib.sitemaps.views.sitemap().Tampilan
django.contrib.sitemaps.views.sitemap()harus mengambil argumen kata kuncisection.
Ini adalah apa yang baris-barus URLconf bersangkutan akan terlihat untuk contoh diatas:
from django.contrib.sitemaps import views
urlpatterns = [
path(
"sitemap.xml",
views.index,
{"sitemaps": sitemaps},
name="django.contrib.sitemaps.views.index",
),
path(
"sitemap-<section>.xml",
views.sitemap,
{"sitemaps": sitemaps},
name="django.contrib.sitemaps.views.sitemap",
),
]
Ini akan otomatis membangkirkan sebuah berkas sitemap.xml yang mengacu kedua sitemap-flatpages.xml dan sitemap-blog.xml. Kelas-kelas Sitemap dan dict sitemaps tidak berubah sama sekali.
If all sitemaps have a lastmod returned by
get_latest_lastmod() the sitemap index will have a
Last-Modified header equal to the latest lastmod.
Anda harus membuat sebuah berkas indeks jika satu dari peta situs anda mempunyai lebh dari 50,000 URL. Dalam kasus ini, Django akan otomatis memberikan nomor peta situs, dan indeks akan mencerminkan itu.
Jika anda tidak menggunakan tampilan peta situs vanilla -- sebagai contoh, jika itu dibungkus dengan penghias cache --anda harus menamai tampilanpeta situs anda dan melewatkan sitemap_url_name ke tampilan indeks:
from django.contrib.sitemaps import views as sitemaps_views
from django.views.decorators.cache import cache_page
urlpatterns = [
path(
"sitemap.xml",
cache_page(86400)(sitemaps_views.index),
{"sitemaps": sitemaps, "sitemap_url_name": "sitemaps"},
),
path(
"sitemap-<section>.xml",
cache_page(86400)(sitemaps_views.sitemap),
{"sitemaps": sitemaps},
name="sitemaps",
),
]
Penyesuaian cetakan¶
Jika anda berharap menggunakan cetakan berbeda untuk setiap peta situs atau indeks peta situs tersedia pada situs anda, anda mungkin menentukan itu dengan melewatkan parameter template_name ke tampilan sitemap dan index melalui URLconf:
from django.contrib.sitemaps import views
urlpatterns = [
path(
"custom-sitemap.xml",
views.index,
{"sitemaps": sitemaps, "template_name": "custom_sitemap.html"},
name="django.contrib.sitemaps.views.index",
),
path(
"custom-sitemap-<section>.xml",
views.sitemap,
{"sitemaps": sitemaps, "template_name": "custom_sitemap.html"},
name="django.contrib.sitemaps.views.sitemap",
),
]
Tampilan ini mengembalikan instance TemplateResponse yang mengizinkan anda dengan mudah menyesuaikan data tanggapan sebelum membangun. Untuk rincian lebih, lihat TemplateResponse documentation.
Variabel konteks¶
Ketika penyesuaian cetakan untuk tampilan index() dan sitemap(), anda dapat bergantung padavariabel konteks berikut.
Indeks¶
The variable sitemaps is a list of objects containing the location and
lastmod attribute for each of the sitemaps. Each URL exposes the following
attributes:
location: The location (url & page) of the sitemap.lastmod: Populated by theget_latest_lastmod()method for each sitemap.
Peta situs¶
Variabel urlset adalah daftar dari URL yang harus muncul dalam peta situs. Setiap URL menampilkan atribut-atribut seperti ditentukan dalam kelas Sitemap:
alternateschangefreqitemlastmodtempatprioritas
The alternates attribute is available when i18n and
alternates are enabled. It is a list of other language
versions, including the optional x_default fallback, for each
URL. Each alternate is a dictionary with location and lang_code keys.
The item attribute has been added for each URL to allow more flexible
customization of the templates, such as Google news sitemaps. Assuming
Sitemap's 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 version="1.0" encoding="UTF-8"?>
<urlset
xmlns="https://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:news="https://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>