Receive our weekly advanced programming tips for FREE
How to create a sitemap in DJango
| 0 votes
Autor: bookkeeper
Chapter: Django

Django has already a sitemap framework and it's very easy!

1. Create a and create a Sitemap class

from django.contrib import sitemaps
import datetime

class Sitemap(sitemaps.Sitemap):
    def __init__(self, names):
        self.names = names

    def items(self):
        return self.names

    def changefreq(self, obj):
        return 'weekly'

    def lastmod(self, obj):

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

It will be a sitemap for our main site

2. Modify the main

from sitemap import *

urlpatterns = patterns('',
 url('imprint', 'blog.views.imprint', name='homepage_imprint'),
 url('archive', 'blog.views.archive', name='homepage_archive'),

sitemaps = {
    'pages':Sitemap(['homepage_imprint', 'homepage_archive']),

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

Sitemap constructor expect a list of url names which should be shown.

To add some of your model just added to

We assume we have a model Blog, modify like this:

from blog.models import Blog

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

    def items(self):
        return Blog.objects.all()

    def lastmod(self, obj):

And modify like:

sitemaps = {
 'site':Sitemap(['name_of_url', 'name_of_url']),

That's it!