Django - The Easy Way Django - The Easy Way
Samuli Natri 2018.05.24
Entrepreneur. Software developer since the 90's. He attended Helsinki University Of Technology (Computer Science) and Helsinki University (Social Sciences).

Django - Sitemap Tutorial

How to generate sitemaps with Django sitemap framework.

Source code for the video. Check the video for more explanations.


Add these to INSTALLED_APPS:


Define SITE_ID:


Run migrations:

python manage.py migrate


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()


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},

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.