How do you create a sitemap index in Django?

by genevieve_boehm , in category: SEO , a year ago

How do you create a sitemap index in Django?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by maci , a year ago

@genevieve_boehm 

To create a sitemap index in Django, you can follow these steps:

  1. Define a separate sitemap class for each individual sitemap using the django.contrib.sitemaps.Sitemap base class.
1
2
3
4
5
6
7
from django.contrib.sitemaps import Sitemap

class BlogSitemap(Sitemap):
    # define methods for sitemap generation here

class NewsSitemap(Sitemap):
    # define methods for sitemap generation here


  1. Create a SitemapIndexView view that renders an XML file containing links to each individual sitemap.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from django.contrib.sitemaps.views import index as sitemap_index_view

class SitemapIndexView(sitemap_index_view):
    sitemaps = {
        'blog': BlogSitemap,
        'news': NewsSitemap,
        # add additional sitemaps here
    }
    
    # override get to add a cache header
    def get(self, request, *args, **kwargs):
        response = super().get(request, *args, **kwargs)
        response['Cache-Control'] = 'max-age=86400'
        return response


  1. Define a new URL pattern that points to the SitemapIndexView.
1
2
3
4
5
6
from django.urls import path
from .views import SitemapIndexView

urlpatterns = [
    path('sitemap.xml', SitemapIndexView.as_view(), name='sitemap')
]


  1. Make sure that you have specified the SITE_ID setting in your Django project's settings.py file. This is required for sitemap generation.
1
SITE_ID = 1


  1. Finally, run the sitemap generation command to generate all sitemaps and the sitemap index.
1
2
3
4
python manage.py makemigrations
python manage.py migrate
python manage.py ping_google
python manage.py generate_sitemaps --verbosity 2


Once complete, the sitemap index should be available at /sitemap.xml, with links to each individual sitemap.