Creating a simple sitemap using Django 3

/ #Django


Sitemaps are an important part of SEO. In this guide, I will show you how to generate one using Django.

Set up

The first thing we need to do in order to use sitemaps, is to include a Django app. Django has built in functionality for this, so we just need to add this to the list of installed apps.

Open up settings.py and add this line to the list:

'django.contrib.sitemaps',

The sitemaps

Inside the main folder of your project, create a file called "sitemaps.py" (Together with urls.py, settings.py, etc).

Add the following contents to it:

from django.contrib.sitemaps import Sitemap
from django.shortcuts import reverse

from blog.models import Post

class StaticViewSitemap(Sitemap):
    def items(self):
        return ['frontpage'', 'contact']
    
    def location(self, item):
        return reverse(item)

class PostSitemap(Sitemap):
    def items(self):
        return Post.objects.all()
    
    def lastmod(self, obj):
        return obj.created_at

First, I just want to say that this is just an example of how this could be done. In my case, I have two static views (frontpage and contact) and my blog has a model called Post. I get all the post objects and add a last modified value to it.

I use the "reverse" function from Django to get the full path to the posts and pages.

Adding the sitemaps to the urls

Already we're at the last step of this procedure.

Inside the urls.py file, we need to import a few things.

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

The first thing we import here is the functionality from Django and then we import the two sitemaps we just created.

Next, we need to make a dictionary with the two sitemaps:

sitemaps = {'static': StaticViewSitemap, 'post': PostSitemap}

Then, we can just append it as a path inside the url patterns.

path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),

If you now go to http://127.0.0.1:8000/sitemap.xml, you should see the two sitemaps.

Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.