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

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

1. Create a sitemap.py 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):
        return datetime.datetime.now()

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

It will be a sitemap for our main site

2. Modify the main url.py

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 sitemap.py

We assume we have a model Blog, modify siemap.py 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):
        return obj.date

And modify url.py like:

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

That's it!