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.