A Beginner’s Guide to Creating Sitemaps in Django
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')…