Search code examples
pythondjangositemapdjango-sitemaps

how do I add homepage to Django sitemap?


The sitemap given sitemap class generates a sitemap at the location, example.com/sitemap.xml

from django.contrib.sitemaps import Sitemap from blog.models import Entry for the given Sitemap class,

class BlogSitemap(Sitemap):
    changefreq = "never"
    priority = 0.5

    def items(self):
        return Entry.objects.filter(is_draft=False)

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

The generated sitemap contains all the objects in the Blog model but not the content outside of the Queryset, How do I add the homepage to the sitemap?

urls

from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import BlogSitemap


sitemaps = {
    'blog': BlogSitemap
}
urlpatterns = [
    url(r'^$', 'blog.views.home'),
    url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
        name='django.contrib.sitemaps.views.sitemap'),
]

Solution

  • Create a sitemap for static views:

    class StaticViewSitemap(sitemaps.Sitemap):
        priority = 0.5
        changefreq = 'daily'
    
        def items(self):
            return ['home']
    
        def location(self, item):
            return reverse(item)
    

    This assumes you have url pattern for the homepage with name "home"

    url(r'^$', views.homepage, name="home"),
    

    Then add the StaticViewSitemap to the sitemaps dict in your urls.py.

    sitemaps = {
        'blog': BlogSitemap,
        'static': StaticViewSiteMap,
    }