A sitemap helps search engines better index your website by providing a structured view of your content. Here’s how to implement it in Django:

Enable the Sitemap framework

First, add the sitemap framework to your Django project’s settings.py:


INSTALLED_APPS = [
    ...
    'django.contrib.sites',
    'django.contrib.sitemaps',
]

SITE_ID = 1

Create the Sitemap class

Create a new file sitemaps.py in your app directory:


from django.contrib.sitemaps import Sitemap
from django.urls import reverse
from .models import Article  # Example model

class ArticleSitemap(Sitemap):
    changefreq = "weekly"
    priority = 0.8

    def items(self):
        return Article.objects.filter(is_published=True)

    def lastmod(self, obj):
        return obj.updated_at

class StaticSitemap(Sitemap):
    priority = 0.5
    changefreq = "daily"

    def items(self):
        return ['home', 'about', 'contact']  # Your static URL names

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

Configure URLs

Add sitemap URLs to your main urls.py:


from django.contrib.sitemaps.views import sitemap
from .sitemaps import ArticleSitemap, StaticSitemap

sitemaps = {
    'articles': ArticleSitemap,
    'static': StaticSitemap,
}

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

Model requirements

Ensure your models have either a get_absolute_url() method or a defined location() method in their Sitemap class:


class Article(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField()
    
    def get_absolute_url(self):
        return reverse('article-detail', args=[self.slug])

Testing

Your sitemap will now be available at /sitemap.xml. Verify it works by:

  • Accessing the URL in your browser
  • Checking the XML output format
  • Validating that all expected URLs are included

Remember to add your sitemap URL to your robots.txt file:


Sitemap: https://yoursite.com/sitemap.xml

This implementation provides a good foundation for SEO and can be expanded based on your specific needs.

Categorized in:

Short answers,

Last Update: 19/01/2025