How to Add a Sitemap to Your Django Site

If you would like to add a sitemap to your project so that Google can easily crawl and index the content of your website for SEO purposes, then this can be achieved using the following steps.

Add the sitemaps to the list of installed apps. It makes sense for this to be added at the bottom of the pre-installed apps that come as part of a standard 'django-admin startproject <my_project_name> .' setup. This should be before any third party or project apps.


    'django.contrib.sitemaps',  # Add

Next up, let's create the sitemap within the app that you would like to create the sitemap for. In my case, I have a Category and a Post model within my blog app.

# blog/

from django.contrib.sitemaps import Sitemap
from django.urls import reverse
from blog.models import Category, Post

class CategorySitemap(Sitemap):
    changefreq = 'daily'
    priority = 0.5

    def items(self):
        return Category.objects.all()

class PostSitemap(Sitemap):
    changefreq = 'daily'
    priority = 0.5

    def items(self):
        return Post.objects.filter(status=1).order_by('-publish_date')

    def lastmod(self, obj):
        return obj.updated_date

Finally, we will just need to wire this up within the project's file. My project is called 'ab_back_end'.

# ab_back_end/

from django.contrib.sitemaps.views import sitemap
from blog.sitemap import CategorySitemap, PostSitemap

urlpatterns = [
    ...  # Block of your project's urls

# Represents the sitemaps that you previously created within
sitemaps = {
    'categories': CategorySitemap,
    'posts': PostSitemap,

# Append the sitemaps to your urlpatterns list.
urlpatterns += [
    path('sitemap.xml', sitemap, {'sitemaps': sitemaps},

That's it! You should now be able to access your site at /sitemap.xml