A Beginner’s Guide to Creating Sitemaps in Django

Sevdimali
Towards Dev
Published in
3 min readApr 25, 2023

This article briefly explains how to create a sitemap for static and dynamic content in your Django application.

Sitemap is a very important part of modern web applications. It helps search engines index your website and also it helps to get better at SEO which will help you to go up in search results.

We are lucky that Django has a built-in solution for it.

Initially, let's create our demo project. I will create two models: Author and Article.

We will also create detail views for these models and one static page.

models.py

from django.db import models
from django.urls import reverse
import uuid


class Base(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

class Meta:
abstract = True


class Author(Base):
name = models.CharField(max_length=100)
bio = models.TextField()
slug = models.SlugField(unique=True, default=uuid.uuid4)

def __str__(self):
return self.name

def get_absolute_url(self):
return reverse('author_detail', args=[self.slug])


class Article(Base):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
body = models.TextField()
slug = models.SlugField(unique=True, default=uuid.uuid4)

def __str__(self):
return self.title

def get_absolute_url(self):
return reverse('article_detail', args=[self.slug])

views.py

from django.shortcuts import render, get_object_or_404, HttpResponse
from article.models import Article, Author


def article_detail(request, slug):
post = get_object_or_404(Article, slug=slug)
return render(request, 'article_detail.html', {'post': post})


def author_detail(request, slug):
post = get_object_or_404(Author, slug=slug)
return render(request, 'author_detail.html', {'post': post})


def about_us(request):
return HttpResponse("About Us Page!")

urls.py

from django.urls import path
from article.views import article_detail, author_detail, about_us

urlpatterns = [
path('article/<slug:slug>/', article_detail, name='article_detail')…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Python Developer, who loves to share ideas, contribute open source, and play chess. Sharing at least one article in every week. Sometimes more😉

Recommended from Medium

Lists

See more recommendations