Django Sitemap - A quick start guide
In this tutorial, I put together some simple steps to get your Django application sitemap up and running in no time.
1. Enable the "sites" framework:
To use the Django sitemap framework, you first need to enable the "sites" framework:
Edit settings.py and add the following to your INSTALLED_APPS (this will add the sites and sitemap apps):
# settings.py INSTALLED_APPS = [ ... 'django.contrib.sites', 'django.contrib.sitemaps', ... ]
Add the following to your settings.py to define a SITE_ID:
# settings.py SITE_ID = 1
Run python manage.py migrate to create the "sites" framework tables.
In Django Admin, access /admin/sites/site/1/ and change the domain to your domain name.
2. Define the get_absolute_url() method in your models
Define the get_absolute_url() method for all the models you have a "view" page that loads an instance of that model (Eg: a single blog post). This will tell Django how to calculate the canonical URL for an object:
# models.py class Post(models.Model): def get_absolute_url(self): return reverse('post', args=[self.slug])
3. Create a sitemaps file
Create a file called sitemaps.py in the same directory of your root URLconf file (urls.py).
In sitemaps.py, define the endpoints you want to include in your sitemap. In the following example, I included the endpoints for a blog system:
# sitemaps.py from django.contrib import sitemaps from django.urls import reverse from my_app.models import Post # This defines the endpoints for single blog posts class PostSitemap(sitemaps.Sitemap): protocol = "https" # optional def items(self): return Post.objects.all() def lastmod(self, obj): # optional return obj.published_at # This defines the endpoints for static pages like the home and about pages class StaticViewSitemap(sitemaps.Sitemap): protocol = "https" # optional def items(self): return ['home', 'about'] def location(self, item): return reverse(item) sitemaps = { 'posts': PostSitemap, 'static': StaticViewSitemap, }
4. Change URLconf to activate sitemap generation
Edit your urls.py and make sure that the URLs you want to include in your sitemap have a name.
# urls.py urlpatterns = [ path('', home_page, name='home'), path('about/', about_page, name='about'), path('<slug>/', post_view, name='post'), ]
Include the sitemaps you created in step 3 to your urls.py.
# urls.py from django.contrib.sitemaps.views import sitemap from .sitemaps import sitemaps urlpatterns = [ path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path('', home_page, name='home'), path('about/', about_page, name='about'), path('<slug>/', post_view, name='post'), ]
5. Generate the sitemap
Browse yourwebsite.com/sitemap.xml to generate the sitemap!