-->

Create sitemap using Django sitemap framework

By: Varghese Chacko 2 years, 8 months ago

The django sitemap framework is very flexible. We can use it to create sitemap for any item in thedatabase, along with custom configurations. The very basic step is to add django.contrib.sitemaps to the installed apps. Then it is better to have our own sitemaps.py. In the sitemaps.py, we have to create a class by inheriting the class Sitemap from django.contrib.sitemaps. In this class we can define our properties for entries in the sitemap.

The class Sitemap lets us define following methods/properties in the class to be used with the sitemap.

  1. item - it is a method that returns a list of items to be processed in other methods. We can return a queryset or list of database objects. 
        def items(self):
            """Blog posts."""
            return BlogPost.objects.order_by('-pk').all()
    ​
  2. location - it is a method or attribute and is optional. If we define as a method, it takes one object from the array returnedby the method items. The returnedurl will be absolute, but without protocol and domain name. Our case,I am showing an example for blog detailspage.
        def location(self, obj):
            """Location url."""
            return reverse("blog_post_detail", kwargs={'slug': obj.slug})​
  3. protocol - It is an optional attribute to define if the site  is http or https. By default, it uses same protocol asthe request to sitemap.
  4. lastmod - An optional attribute or method toset the last modified time. In case we want to get the last modified time from database, we have to return corresponding field from the item object like
        def lastmod(self, obj):
            """Last modified."""
            return obj.publish_date​
  5. changefreq - optional attribute/method. It could be any of 
    'always'
    'hourly'
    'daily'
    'weekly'
    'monthly'
    'yearly'
    'neve​r'
     
  6. priority - itis also an optional method/attribute. For example 
        def priority(self, item):
            """Priority."""
            return self.priority_dict.get(item, 0.7)​

Now we can add the sitemap class to sitemaps like

sitemaps = {
    'blogpost': PostSitemap,

}

Let us combine  all we have discussed now and make our sitemap.py as:

"""Sitemap for ATEMON Blog."""

from django.contrib.sitemaps import Sitemap
from django.core.urlresolvers import reverse
from mezzanine.blog.models import BlogPost


class PostSitemap(Sitemap):
    """Sitemap for blogposts."""

    protocol = 'https'
    changefreq_dict = {"home": 'yearly'}
    priority_dict = {"home": 1.0}

    def items(self):
        """Blog posts."""
        return BlogPost.objects.order_by('-pk').all()

    def lastmod(self, obj):
        """Last modified."""
        return obj.publish_date

    def location(self, obj):
        """Location url."""
        return reverse("blog_post_detail", kwargs={'slug': obj.slug})

    def changefreq(self, item):
        """Change frequency."""
        return self.changefreq_dict.get(item, 'monthly')

    def priority(self, item):
        """Priority."""
        return self.priority_dict.get(item, 0.7)


sitemaps = {
    'blogpost': PostSitemap,
}

Mow we can addthe blog to urls.py as

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

...

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

Our custom sitemap is ready!

Let us talk!

We take the vision which comes from dreams and apply the magic of science and mathematics, adding the heritage of our profession and our knowledge to create a design.