wagtail の sitemap 出力設定をしてみたので、手順を記載します。
参考
- Sitemap generator — Wagtail 1.7 documentation
- Model Reference — Wagtail 1.7 documentation
- django - Custom Wagtail Sitemap - Stack Overflow
wagtail.contrib.wagtailsitemaps の設定
wagtail では、sitemap 出力のためのアプリケーションが用意されています。
このアプリケーションを追加し、urls.py に URL を定義します。
INSTALLED_APPS に追加
INSTALLED_APPS
に wagtail.contrib.wagtailsitemaps
を追加します。
django.contrib.sitemaps
の sitemap.xml テンプレートを使用しているので、django.contrib.sitemaps
もなければ追加します。
INSTALLED_APPS = [
'wagtail.contrib.wagtailsitemaps',
'django.contrib.sitemaps',
]
django.contrib.sitemaps
を追加していない状態だと、TemplateDoesNotExist
が発生します。
urls.py に sitemap.xml を追加
urls.py に sitemap.xml の定義を追加します。
from wagtail.contrib.wagtailsitemaps.views import sitemap
urlpatterns = [
...
url(r'^sitemap\.xml$', sitemap),
]
- 補足
で動作確認をしたところ、以下のような sitemap.xml の出力となりました。Django 2.1.8 wagtail 2.3
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>https://mutter.monotalk.xyz/</loc> <lastmod>2018年3月21日17:25</lastmod> <changefreq/> <priority/> </url> <url> <loc>https://mutter.monotalk.xyz/about</loc> <lastmod>2018年3月21日21:32</lastmod> <changefreq/> <priority/> </url> <url> <loc>https://mutter.monotalk.xyz/posts</loc> <lastmod>2018年3月21日16:59</lastmod> <changefreq/> <priority/> </url>
lastmod
に日本語が設定されるのは、sitemap.xml の形式として不正になります。
以下、templateとして別途xmlを準備して、urls.pyを書きかえたところ正常に出力されました。
from wagtail.contrib.wagtailsitemaps.views import sitemap urlpatterns = [ ... url(r'^sitemap\.xml$', sitemap, {'template_name': 'custom_sitemap.html' }), ]
<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/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 %} </url> {% endfor %} {% endspaceless %} </urlset>
http://127.0.0.1:8000/sitemap.xml
にアクセスする
ローカルサーバーを立ち上げて、sitemap.xml にアクセスすると以下の内容のxml が出力されます。
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>http://localhost/</loc><lastmod>2018-03-10</lastmod></url>
<url><loc>http://localhost/posts/</loc><lastmod>2018-03-10</lastmod></url>
<url><loc>http://localhost/posts/3a211ddd211948452de1613f82543eed/</loc></url>
<url><loc>http://localhost/posts/a516f27b3fd13e5a24ff36327142a613/</loc></url>
<url><loc>http://localhost/posts/6c287eab5aa45415bf5c50df1e61a47f/</loc></url>
<url><loc>http://localhost/about/</loc><lastmod>2018-03-10</lastmod></url>
</urlset>
ページごとにsitemap.xml の出力内容を変更する
Page クラスに、get_sitemap_urls
ファンクションを定義して、出力フィールドを設定すると出力内容をカスタマイズできるようです。
def get_sitemap_urls(self):
return [
{
'location': self.full_url,
'lastmod': self.latest_revision_created_at,
'changefreq': 'monthly',
'priority': .5
}
]
以上です。
コメント