Django - Sitemap Framework - GeeksforGeeks

04 Jul, 2021
Prerequisites: Django Introduction and Installation 
Search-Engines crawls and indexes the site’s URLs to show them in their search results. Search-Engines recommend the explicit submission of an XML file consisting of all the important and updated URLs of your site for faster crawling and indexing. Django comes up with a Sitemap Framework to ease out the process of generating the XML file and pinging the search engines to crawl. 
Let’s understand the sitemap creation using Geeks For Geeks as an example. Suppose 100 articles are published each day on Geeks For Geeks, and we have to create an XML file consisting of the URLs of those articles.
Follow  Django Introduction and Installation to set up a virtual environment and install Django.
Step 1: Start a project by following command
django-admin startproject geeks_site
Step 2: Change directory to geeks_site
cd geeks_site
Step 3: Create an app named blog
python manage.py startapp blog
Step 4: Add your app to the settings.py
Python3
INSTALLED_APPS = [    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'blog.apps.BlogConfig',]
Step 5: Create a Model named Article in the blog app
Fields :title: To store the titles of the Article objectslastedit_date: To store the last updated dates of Article objects
title: To store the titles of the Article objects
lastedit_date: To store the last updated dates of Article objects
Method :get_absolute_url: Returns the absolute URL pointing to an object
get_absolute_url: Returns the absolute URL pointing to an object
models.py
Python3
class Article(models.Model):    title = models.CharField(max_length=200)    lastedit_date = models.DateTimeField()      def get_absolute_url(self):        return "/p/%i/" % self.id
Step 6: Register your model in blog/admin.py so that it shows up in the admin panel.
admin.py
Python3
# blog/admin.pyfrom django.contrib import admin from .models import Article  admin.site.register(Article)
Step 7: Now, To migrate all your changes and start the server, run the following commands in your terminal 
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
Create a superuser account to log in to the admin panel
python manage.py createsuperuser
Now, Visit the admin panel at http://127.0.0.1:8000/admin/
Now, Let’s Install and Initialize the Django’s Sitemap Framework
To use the Sitemap Framework, you will need to make the following changes to your settings.py :
Sitemap Framework is not enabled by default in Django, so add the following to INSTALLED_APPS
django.contrib.sitemaps
Sitemap Framework uses another Django’s inbuilt Sites Framework for it’s functioning. Also, add the following to INSTALLED_APPS
django.contrib.sites
Then add the following after the INSTALLED_APPS list
SITE_ID = 1
Python3
# Application definitionINSTALLED_APPS = [    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'django.contrib.sites',      'django.contrib.sitemaps,    'blog']  SITE_ID = 1
Step 1: Create a file named sitemap.py in your blog app
Step 2: Create a Sitemap class for your Article Model in sitemap.py
ArticleSitemap class overwrites the following two methods of Sitemap classitems: returns all the article objects, whose URLs will be included in XML filelastmod: returns the last modified date of an object using the lastedit_date field of Article Model in blog app
items: returns all the article objects, whose URLs will be included in XML file
lastmod: returns the last modified date of an object using the lastedit_date field of Article Model in blog app
sitemap.py
Python3
from django.contrib.sitemaps import Sitemapfrom .models import Article  class ArticleSitemap(Sitemap):    def items(self):        return Article.objects.all()            def lastmod(self, obj):        return obj.lastedit_date
Step 3: Add these lines to your blog/urls.py.
Python3
from django.contrib.sitemaps.views import sitemapfrom blog.sitemap import ArticleSitemapfrom django.urls import path    path('sitemap.xml', sitemap, {'sitemaps': {'article' : ArticleSitemap}},     name='django.contrib.sitemaps.views.sitemap')
Here ‘sitemap.xml‘ points to the sitemap view of the Sitemap Framework’s with ArticleSitemap class created in the previous step as required parameter in the specified format, i.e. {‘sitemaps’: {‘article’ : ArticleSitemap}
Now, again migrate all your changes and start the server
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
Step 4: In the Article section, create some Articles. After clicking the add button you will see the below fields. 
when you will click the Sites section you will something like this
Make the following changes to Sites section of Admin Panel
Now visit at http://127.0.0.1:8000/sitemap.xml in your local machine. The final XML file consisting of all URLs will be rendered as :
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python