Sitemaps and Django

Today I was playing at work with sitemap generation using Django and hit a wall. Django’s sitemap framework looks easy enough and I believe is powerful and flexible; it helps you generate the XML for your models and flatpages with very little effort. The problem that I encountered was because I am not using flatpages at all, I encountered some limitations for what I needed to do. Maybe I’m missing something, I don’t know.

Now, I’m not claiming to be a Python master, but here’s the solution I came up with. If you know of a better way, let me know. If anything, I hope this helps someone in the same situation.

So, according to the sitemap documentation, after you set up the framework, you can generate a simple sitemap.xml with the following code:

from django.contrib.sitemaps import Sitemap
from mysite.blog.models import Entry

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

Easy enough, right? Well, it turns out that I couldn’t figure out from the documentation how to include a group of pages that don’t have models and that are not using the flatpages framework. I am simply mapping from urls to views to templates. So let’s say that you are on the same boat and want to also include things like /about/ or /contact/ in your sitemap.xml, simply add a class similar to this:

class PagesMap(Sitemap):
    changefreq = 'never' #or pick your frequency
    priority = 0.5 #or pick your priority
    page_dict = {
        'Home':'/',
        'About':'/about/',
        'News':'/news/',
        'Services':'/services/',
        'Contact':'/contact/'
    }

    def items(self):
        return self.page_dict.keys()

    def location(self, url):
        return self.page_dict[url]

    def lastmod(self, obj):
        return datetime.datetime.now()

Simple, right? Again, if I am missing something and there’s a better or a “correct” way, let me know. It did the trick for me.

Happy coding!


About this entry