Sitemap.xml with newses and static pages in django
October 6, 2009 | frameworks, pythonauthor: Karol Zielinski | comments: 2 | views: 1564
Tags: django, google, python, search engine, sitemap
It’s really easy to create simple sitemap.xml in django. You can follow the instructions from this site or just google it. However… it’s a bit more complicated when you want to create simple.xml file with newses and some static pages.
Ok, first… do we really need simple.xml in our website? Yes, we do. Because of search engines.
Now, how to create it in django? Use ‘django.contrib.sitemaps.views.sitemap’.
Ok, now… creating simple sitemap.xml is really simple:
However… what if you want to have all the pages (dynamic newses and static pages) from your site in one sitemap.xml? You need to do something more…
cd /home/workspace/my_project vim sitemaps.py
and add there:
from django.contrib.sitemaps import Sitemap
from my_project.main.models import News
from datetime import datetime
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
class AbstractSitemapClass:
freq = ''
changefreq = 'daily'
prio = None
url = None
def get_absolute_url(self):
return self.url
class BlogSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
pages = {
'main' : '/',
'contact' : '/contact/',
'about-us' : '/about-us/',
'art-design' : '/art-design/',
'life-style' : '/life-style/',
}
def items(self):
newses2feed = News.objects.order_by('-dateCreated')
newses2feed = list(newses2feed)
for each_page in self.pages.keys():
new_class = AbstractSitemapClass()
new_class.freq = 'weekly'
new_class.prio = 0.7
new_class.url = self.pages[each_page]
newses2feed.append(new_class)
return newses2feed
def lastmod(self, obj):
try:
date = obj.dateCreated
except AttributeError:
date = datetime.now()
return date
def changefreq(self, obj):
obj_freq = None
try:
obj_freq = obj.freq
except AttributeError:
pass
if obj_freq:
return obj_freq
else:
return 'monthly'
def priority(self, obj):
obj_prio = None
try:
obj_prio = obj.prio
except AttributeError:
pass
if obj_prio:
return obj_prio
else:
return 0.5
and now:
vim urls.py
and add there (somewhere at the beginning):
from my_project.sitemaps import BlogSitemap
sitemaps = {
'news': BlogSitemap,
}
and new pattern:
(r'^sitemap.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
That’s all.
Btw… don’t forget pinging google after each change in sitemap.xml.
Hello, I'm Karol Zielinski, internet evangelist, an entrepreneur, project manager and a web developer from Gdynia, Poland. I like creative design, good advertisement, social media and all kind of stuff around the web.
October 6, 2009, 5:42 am
Do you have any code to implement a django sitemap in php
July 14, 2010, 4:26 am
Nice solution and article.