Dori's Python Life in Words Journal

Adding a sitemap to the blog


A sitemap provides search engines with a structure of our website and helps them to index our website more effectively. It is a dynamically generated XML file.

The two Django frameworks (sites and sitemaps) need to be added to INSTALLED_APPS.

#blog_project/settings.py

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.sites",
    "django.contrib.sitemaps",
    "django.contrib.staticfiles",
    # custom apps
    "account",
    "blog",
    "core",
    # packages/libraries:
    "taggit",
]

# Sitemap framework
SITE_ID = 1

Legend:

    • "django.contrib.sites": This allows you to associate objects with specific websites that run with your project.
    • "django.contrib.sitemaps": This is the actual Django sitemap framework.
    • SITE_ID: This SITE_ID is to use the django.contrib.sites framework.

We need to perform migrations to implement the Django sitemap framework inside the database: python manage.py migrate.

#blog/sitemaps.py

from django.contrib.sitemaps import Sitemap

from blog.models import Post


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

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

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

Legend:

    •  PostSitemap: Is our custom sitemap, which we inherit from Sitemap class.
    • changefreq: This attribute indicates the frequency of changes to your post pages.
    • priority: This attribute indicates their importance in your website.
    • items(): This method defines the QuerySet of sitemap objects. It automatically calls the get_absolut_url() method in the model.
    • lastmod(): This method retrieves each object from the items() method and returns the last time the object was modified.
# blog_project/urls.py

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

from blog.sitemaps import PostSitemap

sitemaps = {"posts": PostSitemap}

urlpatterns = [
    path("admin/", admin.site.urls),
    path("blog/", include("blog.urls", namespace="blog")),
    path(
        "sitemap.xml",
        sitemap,
        {"sitemaps": sitemaps},
        name="django.contrib.sitemaps.views.sitemap",
    ),
]

Legend:

    •  sitemaps: This dictionary contains all custom sitemaps.
    •  path("sitemap.xml",...): This path defines a URL pattern that matches the sitemaps.xml pattern and uses the sitemap view to display the XML output.

 


Designed by BootstrapMade and modified by DoriDoro