Doro's Python Life in Words Journal

Expanding your sitemap with Tags


Currently my blog has all the posts inside the sitemap. Let's improve my blog by adding all tags to the sitemap. By adding all tags to the sitemap, this could significantly improve the SEO optimisation of the blog.

The file sitemaps.py has already been created and the PostSitemap is defined. Now I add the TagSitemap.

# blog/sitemaps.py

from django.contrib.sitemaps import Sitemap
from django.urls import reverse
from taggit.models import Tag

class TagSitemap(Sitemap):
    changefreq = "monthly"
    priority = 0.6

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

    def location(self, obj):
        return reverse("blog:post_list_by_tag", kwargs={"tag_slug": obj.slug})

Legend:

    • location(): This can be used as an optional method or attribute. In our case, this method returns the absolute path of a given object given by the items() method.
    • reverse(): Use this if you want to use something like the url template tag in your code. Pass the URL pattern name as the viewname attribute.

Add the newly created custom sitemap to the sitemaps dictionary. This will be passed to the URL.

# blog/urls.py

from django.contrib.sitemaps.views import sitemap

from blog.sitemaps import PostSitemap, TagSitemap

sitemaps = {"posts": PostSitemap, "tags": TagSitemap}

urlpatterns = [
    path(
        "sitemap.xml",
        sitemap,
        {"sitemaps": sitemaps},
        name="django.contrib.sitemaps.views.sitemap",
    ),
]


Designed by BootstrapMade and modified by DoriDoro