Sitemap –

Sitemap protocol allows a webmaster to inform search engines about URLs on a website that are available for crawling. A Sitemap is an XML file that lists the URLs for a site. It allows webmasters to include additional information about each URL: when it was last updated, how often it changes. This allows search engines to crawl the site more efficiently and to find URLs that may be isolated from the rest of the site’s content.

Add sitemaps to INSTALLED_APPS –

Django also comes with a sitemaps creator go to the blog app directory and add sitemaps to installed apps in settings file

Python3




INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
    # adding in installed apps
    'django.contrib.sitemaps',
 
]


Create Sitemap – 

Create a file sitemaps.py and paste the below code.

Python3




from django.contrib.sitemaps import Sitemap
from .models import posts
 
# sitemap class
class blogSitemap(Sitemap):
# change frequency and priority
    changefreq = "daily"
    priority = 1.0
 
    def items(self):
        return posts.objects.filter(status = 1)
 
    def lastmod(self, obj):
        return obj.updated_on


Add absolute URL to model – 

Sitemap generated should have urls for our posts so we need to add a simple function to our model so that we sitemap library can generate posts urls

Python3




# add it in your model for which you want to generate sitemap
def get_absolute_url(self):
        from django.urls import reverse
        return reverse("post_detail", kwargs ={"slug": str(self.slug)})


Routing for sitemap –

Now to generate the sitemap url, Go to urls.py file of the and add the route

Python3




# adding sitemap libraries
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import blogSitemap
 
blogsitemap = {
"blog": blogSitemap, }
 
urlpatterns = [
.....
    # urls handling site maps
    path("sitemap.xml", sitemap, {"sitemaps": blogsitemap}, name ="sitemap"),
.....
]


Now you can see RSS feed and Sitemaps at assigned urls

Sample Sitemap

Sample Sitemap



How to add RSS Feed and Sitemap to Django project?

This article is in continuation of Blog CMS Project in Django. Check this out here – Building Blog CMS (Content Management System) with Django

Similar Reads

RSS (Really Simple Syndication) Feed

RSS (Really Simple Syndication) is a web feed that allows users and applications to access updates to websites in a standardized, computer-readable format. These feeds can, for example, allow a user to keep track of many different websites in a single news aggregator. Django comes with an library to create atom feed for our blog....

Sitemap –

...

Contact Us