How to Generate Sitemap in Django?

Published On: 08/10/2022 | Category: Django

Hi Dev,

This is a short guide on django generate sitemap xml file tutorial example. you can see how to generate sitemaps with django sitemap framework. Here you will learn how to generate sitemap in django. I would like to show you django sitemap example tutorial. you will do the following things for how to generate a dynamic django sitemap.

An XML file called a sitemap is what search engines use to intelligently crawl your website. It not only gives details about the files and pages you consider significant, but it also indicates when and how frequently the page is updated.

If you're using Django, the sites and sitemap frameworks will automatically generate your Django sitemap.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example

Step 2: Create a App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python startapp core

Step 3: Update

In this step we require to do two things in our file, One is our installed app name Add the below lines to your file:

Next, you need to add it in the file as follows:


    'django.contrib.sites', #new
    'django.contrib.sitemaps', #new

# Define SITE_ID:

Step 4: Create a Model

In this step we will require the database model for storing contacts.Open the core/ file and add the following code:

from django.db import models
from django.contrib.auth.models import User

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)

    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)})

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python makemigrations
python migrate

Step 5: Creating the Sitemaps File

In this step, we need to create set the sitemap protocol, changefreq and priority in PostSitemap class and fetch the all record from post table.

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

class PostSitemap(Sitemap):
    changefreq = "daily"
    priority = 1.0
    protocol = 'https'

    def items(self):
        return Post.objects.all()

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

Step 6: Creating the Views

In this step, we need to create the views for performing the fetch record to the database.Open the core/ file and add:

from django.shortcuts import render
from .models import Post
from django.views.generic import DetailView
from . import models
from django.views.generic.list import ListView

class PostListView(ListView):
    model = Post
    template_name = 'home.html'
    context_object_name = 'posts'

class PostDetail(DetailView):
    model = Post
    template_name = 'detail.html'
    slug_field = 'slug'

Step 7: Creating the Templates

Next, then with your text editor create new templates files: core/templates/home.html file and the add:



    {% for post in posts %} <li> <a href="{{ post.get_absolute_url }}">{{ post }}</a> </li> {% endfor %} </ul>
<h1>{{ post.title }}</h1>

Step 8: Creating URLs

In this section, we need a file within the apis app however Django doesn't create one for us with the startapp command. Create core/ with your text editor and paste below code.

from django.urls import path, include
from . import views
from .sitemaps import PostSitemap
from django.contrib.sitemaps.views import sitemap

sitemaps = {
    "posts": PostSitemap,

urlpatterns = [
    path("sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="sitemap"),
    path("post", views.PostListView.as_view(),name='post'),
    path("post-details/<slug>", views.PostDetail.as_view(),name='post_detail'),

Next, we will require the modify the your root preoject folder lets update the file.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('core.urls')),

Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver

Next, go to the address with a web browser.

I Hope It will help you....