#django #python #wagtail

Let's have a look at adding a sitemap to your Wagtail website. We can use the Django sitemap app to add one. As usual, we first start with adding it to the list of installed apps in our settings:


2    ...
3    'django.contrib.sitemaps',
4    ...

To finish the installation, we also need to add the URL definitions to url.py:


1from wagtail.contrib.sitemaps.views import sitemap
3urlpatterns = [
4    ...
5    path('sitemap.xml', sitemap),
6    ...
7    # Ensure that the 'sitemap' line appears above the default Wagtail page serving route
8    re_path(r'', include(wagtail_urls)),

That's all you need to do to get it up and running. If you now browse to "/sitemap.xml" on your site, it will return the proper file based on the structure of your site.

You can customize the list of URLs which is included for a page in the sitemap by implementing the get_sitemap_urls function:

In my blog, I only want to include the BlogPost objects which have a publish date which is not empty and is older than today. I've set it up like this:

1class BlogPost(Page):
2    def get_sitemap_urls(self, request):
3        if not self.date or self.date > timezone.now():
4            return []
5        return super(BlogPost, self).get_sitemap_urls(request)

When you return an empty list, it will not include the page in the sitemap.

You can find more info in the Wagtail documentation.