Creating Sitemaps in Django

Django comes with baked-in functionality for generating sitemaps dynamically using the sitemap framework.

A sitemap is an XML file that informs search engines such as Google, the pages of your website, their relevance, and how frequently they are updated. Using sitemaps facilitates crawlers indexing the site, therefore sitemap plays a crucial role in modern SEO (Search Engine Optimization).

In this article, we will learn how to create sitemaps in a Django application.

Creating Sitemaps in Django

Considering the scope of the article I am assuming you have basic knowledge of Django and have a project up and running if not read the following article first.

Installation

Add 'django.contrib.sitemaps' in INSTALLED_APPS setting.

INSTALLED_APPS += ( 'django.contrib.sitemaps',)

Make sure your TEMPLATES setting contains a DjangoTemplates backend whose APP_DIRS options is set to True. It’s in there by default, revert it in case you have changed it.

Creating Sitemap

I am generating a sitemap for a blog application following is the models.py file for reference.

class Post(models.Model):
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True)
    author = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="blog_posts"
    )
    updated_on = models.DateTimeField(auto_now=True)
    content = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=STATUS, default=0)

    class Meta:
        ordering = ["-created_on"]

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        from django.urls import reverse

        return reverse("post_detail", kwargs={"slug": str(self.slug)})

Inside your application create a new file sitemaps.pyand add the following configuration.

from django.contrib.sitemaps import Sitemap
from .models import Post

class PostSitemap(Sitemap):
    changefreq = "weekly"
    priority = 0.8

    def items(self):
        return Post.objects.filter(status=1)

    def lastmod(self, obj):
        return obj.updated_on

The optional changefreq and priority attributes indicate the change frequency of post pages and their relevance  (the maximum value being 1).

Possible values for changefreq, whether you use a method or attribute, are:

  • ‘always’
  • ‘hourly’
  • ‘daily’
  • ‘weekly’
  • ‘monthly’
  • ‘yearly’
  • ‘never’

The items() method returns the querySet of objects to include in this sitemap and lastmod returns a DateTime.

Note that, there is no location method in this sitemap, but you can provide it in order to specify the URL for the objects. By default, location() calls get_absolute_url() on each object and returns the result.

So you must either implement location() on your PostSitemap, or implement
get_absolute_url() on your Post model.

Finally, map the URL for the sitemaps in the project’s urls.py file.

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


sitemaps = {
    "posts": PostSitemap,
}

urlpatterns = [
        ..........
    path("sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="sitemap"),
        .........
]

This tells Django to build a sitemap at /sitemap.xml.

Save the files run the server and visit http://127.0.0.1:8000/sitemap.xml you should see something like this.

Generating sitemap in Django

To explore more visit – https://docs.djangoproject.com/en/3.0/ref/contrib/sitemaps/

Related Articles

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Close