Samuli Natri - Software Developer
menu

Django - Sitemap Tutorial

How to generate sitemaps with Django sitemap framework.

Source code for the video. Check the video for the full explanation.

settings.py

Add these to INSTALLED_APPS:

django.contrib.sites
django.contrib.sitemaps

Define SITE_ID:

SITE_ID = 1

Run migrations:

python manage.py migrate

sitemaps.py

Create sitemaps.py anywhere in your project:

from django.contrib.sitemaps import Sitemap
from blog.models import Post

class PostSitemap(Sitemap):

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

urls.py

Edit the main urls.py file:

from django.contrib.sitemaps.views import sitemap
from base.sitemaps import PostSitemap

sitemaps = {
'posts': PostSitemap,
}

urlpatterns = [
    path('admin/', admin.site.urls),
    path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
         name='django.contrib.sitemaps.views.sitemap'),
]

Define get_absolute_url

The following assumes that you have defined a path for post model in urls.py file:

from blog import views as blog_views

path('post/<int:id>/', blog_views.post, name='post'),

In the blog model add get_absolute_url(self):

from django.urls import reverse

class Post(models.Model):

    title = models.CharField(max_length=255, default='')
    
    ...

    def get_absolute_url(self):
        return reverse('post', args=[str(self.id)])

Visit /sitemap.xml.

Sitemaps For Static Views

Add this class to the sitemaps.py file:

class StaticViewSitemap(Sitemap):

    def items(self):
        return ['about']

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

Add StaticViewSitemap to the sitemaps dictionary in urls.py and make sure that you have a path for the about view:

sitemaps = {
    'posts': PostSitemap,
    'static': StaticViewSitemap, # < here
}
path('about', base_views.about, name='about'),

Check the official documentation for more configuration options.