Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

Creating Sitemaps in Django

3 min read

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/


DJANGO

Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read