from django.contrib.sitemaps import Sitemap
from .models import Post
class PostSitemap(Sitemap):
changefreq = 'weekly'
priority = 0.9
def items(self):
return Post.objects.filter(status='published')
def lastmod(self, obj):
return obj.updated_at
def location(self, obj):
return obj.get_absolute_url()
class StaticViewSitemap(Sitemap):
priority = 0.5
changefreq = 'monthly'
def items(self):
return ['home', 'about', 'contact']
def location(self, item):
from django.urls import reverse
return reverse(item)
from django.contrib.sitemaps.views import sitemap
from django.urls import path
from blog.sitemaps import PostSitemap, StaticViewSitemap
sitemaps = {
'posts': PostSitemap,
'static': StaticViewSitemap,
}
urlpatterns = [
path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap'),
]
Sitemaps help search engines discover and index pages. Django's sitemap framework generates XML sitemaps automatically. I create sitemap classes for each content type, defining items(), lastmod(), changefreq(), and priority(). For large sites, I use sitemap indexes. I configure in urls.py and submit to search engines. Dynamic sitemaps update automatically as content changes. This improves SEO without manual sitemap maintenance. I cache sitemaps for performance on high-traffic sites.