Creating Sitemaps in Django

So I wanted to add a sitemap to my site – and I went looking for a plugin to do it for me.

But I don’t need a plugin! Why? Because Django has sitemap generation built into the framework!

Brilliant!

(that’s why we go with tried and trusted frameworks, if you’re a single dev and time is money!)

So how do we set up sitemaps on your Django site? Well, beloved reader – simply follow these steps:

Update your settings.py

Add this to your INSTALLED_APPS variable. You don’t have to install anything – it is built into Django.

    'django.contrib.sitemaps'

Create sitemaps.py

Then, in the same level as your main url.py file create a file called sitemaps.py and give it it this code:

from django.contrib import sitemaps
from django.urls import reverse

class StaticViewSitemap(sitemaps.Sitemap):
    priority = 0.5
    changefreq = 'daily'

    def items(self):
        return ['website:home',
                'website:pricing',
                'website:join-no-plan',
                'website:contact',
                'website:terms',
                'website:privacy',
                ]

    def location(self, item):
        return reverse(item)

In this example my static pages are in an app called “website” so I have to prepend the view names with “website:” – but yeah, just put in the view names that are applicable for your site.

This is for static pages. There are options for dynamic pages too – just check the docs (link at the bottom).

Update urls.py

Then in your main urls.py add this magic:

from django.contrib.sitemaps.views import sitemap
from .sitemaps import StaticViewSitemap

sitemaps = {
    'static': StaticViewSitemap,
}

# Add this to your urlpatterns variable:
  path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),

Access sitemap.xml

In your favourite browser go to your website and type in sitemap.xml in the url – your sitemap is ready for you!

Wow – I don’t know of another framework where sitemaps come out of the box. Truly Django is batteries included!

There is even documentation! Check it out here: Django Sitemaps

Leave a Reply