return 42;

by Jan Wedel

Sitemaps for Static Views with Arguments

This article explains how to easily pass arguments to reverse() in a static view sitemap in Django, Python's web framework.

I've just recently added a site map to my blog since Google webmaster tools always shows that the site map is missing. So, just for fun, I've added it.

Actually, there is some great documentation here.

So I've added a sitemap sitemaps.py to my main Django project:

from core.sitemap import CoreSitemap
from blog.sitemap import BlogSitemap


sitemaps = {
    'ReturnCode' : CoreSitemap,
    'Blog' : BlogSitemap
}

and added this to the urls.py:

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

(...)

urlpatterns = patterns('',
    url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
    name='django.contrib.sitemaps.views.sitemap')

)

So, BlogSitemap is pretty straight forward according to the documentation examples. CoreSitemap, however, was a bit tricky since I wanted to include some "pages". A page is much like an article but is used as a static content page like site notice or site privacy police. So I wanted to include them within the sitemap. To achieve this, I had to pass arguments to the reverse() method.

So I started with some static pages:

from django.contrib.sitemaps import Sitemap
from django.core.urlresolvers import reverse


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

    def items(self):
        return [
            'blog:index',
            'gridsolver:index'
        ]

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

This works pretty well. However, I needed to pass an argument, namely the slug of that page together with blog:page. So I was assuming (which turned out to be right) that the items returned by itmes(self) were just passed to location. So what I ended up was:

def items(self):
    return [
        ('blog:index', {}),
        ('gridsolver:index', {}),
        ('blog:page', {'slug':'site-notice'}),
        ('blog:page', {'slug':'privacy-police'})
    ]

def location(self, (name, kwargs)):
    return reverse(name, kwargs=kwargs)

So items() returns a list of tuples (pagename, kwargs). kwargs can be an empty map when there is nothing to be passed.


Jan Wedel's DEV Profile