Nov 5, 2024
Posted by:
In a previous article Creating XML sitemaps for your Wagtail website, we learnt how to create a XML sitemap for Wagtail published pages only. Besides Wagtail pages, your site may also be serving some Django static views. To do this create a sitemaps.py file. This can be in your project directory where the root urls.py file is located.
sitemaps.py | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | from datetime import datetime from django.contrib import sitemaps from django.urls import reverse from django.conf import settings class StaticViewSitemap(sitemaps.Sitemap): def items(self): return [ 'about', 'contact'] # List of URL patterns names def location(self, item): return reverse(item) def lastmod(self, item): template_files = { "about": "about.html", "license": "license.html", } # Construct the full path to the template using pathlib template_path = settings.PROJECT_DIR / "templates" / template_files[item] # Get the modification time using pathlib file_mod_time = template_path.stat().st_mtime return datetime.fromtimestamp(file_mod_time) |
Next, update your urls.py file. Import the Sitemap module from wagtail.contrib.sitemaps.sitemap_generator and add it to the sitemaps dictionary.
urls.py | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # urls.py from django.contrib.sitemaps.views import sitemap from django.urls import path from wagtail.contrib.sitemaps.sitemap_generator import Sitemap from .sitemaps import StaticViewSitemap sitemaps = { "wagtail" : Sitemap, "static" : StaticViewSitemap } urlpatterns = [ path('sitemap.xml', sitemap, {"sitemaps" : sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), # other URL patterns ] |
Browse to /sitemap.xml and check that the Django static views are included together with the wagtail pages.