Nov 7, 2024
Posted by:
In a previous article Django static views in wagtail sitemap we learnt how to add views with simple url patterns. What if the url pattern consists of named regular expression groups? For example the urls.py file could contain these paths :
urls.py | |
---|---|
1 2 3 4 5 6 7 8 9 | from django.urls import re_path from . import views app_name = 'training' urlpatterns = [ re_path('pay/(P<product_code(CourseA|CourseB|CourseC))/?$', views.LandingPageView.as_view(), name='pay'), ] |
Change the sitemaps.py file as follows :
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 25 26 27 28 29 30 31 32 33 34 35 | import datetime from django.contrib import sitemaps from django.urls import reverse class StaticViewSitemap(sitemaps.Sitemap): def items(self): """ Use a tuple instead of a dict because dict not hashable as dict key in template_files dict in lastmod method We convert the tuple to a dict in the location method """ return [ ('training:pay', ('product_code', 'CourseA')), ('training:pay', ('product_code', 'CourseB')), ('training:pay', ('product_code', 'CourseC')), def location(self, item): name, t = item return reverse(name, kwargs=dict([t])) def lastmod(self, item): template_files = { ('training:pay', ('product_code', 'CourseA')) : 'training/coursea_landing.html', ('training:pay', ('product_code', 'CourseB')) : 'training/courseb_landing.html', ('training:pay', ('product_code', 'CourseC')) : 'training/coursec_landing.html', } # Construct the full path to the template using pathlib template_path = settings.PROJECT_DIR / "training" / "templates" / template_files[item] # Get the modification time using pathlib file_mod_time = template_path.stat().st_mtime return datetime.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.
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 views are included together with the wagtail pages.