Share with   

Create dynamic sitemap xml file in Python Django for SEO

Here we are going to see how we can create dynamic sitemap using python Django models for increasing SEO and register this sitemap to various Search Engines


Sitemap

A Sitemap is a list of pages of a web site. There are three primary kinds of site map: Site maps used during the planning of a Web site by its designers. Human-visible listings, typically hierarchical, of the pages on a site. Structured listings intended for web crawlers such as search engines.

Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site.

 

Django Sitemap XML File

Django is web framework using python language we can design website or web app and also we can build rest api using Django Rest Framework. When we completely build web app and deploying to the online hosting. After that we need to register this web app to the google search engine or any other search engine. And we also need SEO (Search Engine Optimization) so the sitemap is one of the way to describe the pages urls so that search engines can more intelligently crawl the site.

 

Prerequisite

  1. Install Python

  2. Install Django

 

Create Sitemap XML File

If you do not create django project yet. You can see the article for creating Django Project.

To create dynamic sitemap for your django project follow the steps to add sitemap in django app.

Add this libraries to your django project settings.py file

'django.contrib.sites', 'django.contrib.sitemaps'

INSTALLED_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',
]

If you want to change the base url example.com to any domain name like procodeprogramming.com you need to create Django Site

 

Django Site

In django web app, they already by default use site i.e. SITE_ID - 1 and url is example.com when you register 'django.contrib.sites' to current django project settings

If you want to change with another one here is 2 ways to change the Django Site.

 

Create Django Site and set id to settings.py file

INSTALLED_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',
]

SITE_ID = 2

 

Create sitemap.py file in current django project. I recommend you to place this file where the having settings.py file. So you can easily access and edit the file.

Creating demo django model for register urls to sitemap

from django.db import models

class Articles(models.Model):
    title = models.CharField(max_length=130)
    description = models.TextField()
    created_date = models.DateTimeField(auto_now_add=True, verbose_name="date published")
    modified_date = models.DateTimeField(auto_now=True, verbose_name="date updated")

 

 

Write code under sitemap.py file.

from django.contrib.sitemaps import Sitemap
from api.models import Articles
from django.contrib.sites.models import Site

class Site:
    domain = 'procodeprogramming.com/blog/'

class ArticleSitemap(Sitemap):
    changefreq = "daily"
    priority = 0.5

    def get_urls(self, site=None, **kwargs):
        site = Site()
        return super(ArticleSitemap, self).get_urls(site=site, **kwargs)

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

    def location(self, obj):
        return obj.pk

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

 

Below code is explained you to create dynamic sitemap.xml file. On this code

class Site is used for declaring your domain address and location. If we want to add url like https://procodeprogramming.com/blog/1 to the sitemap i.e. 1 is the ID of article model and just declare others in domain.

class ArticleSitemap is created for sitemap to get absolute dynamic urls to add this urls to sitemap.

In that changefreq is key which shows you the frequency of that url so we can set freq like daily, monthly etc.

Priority tag in sitemap xml file is to signal the importance of pages in website to search engine. Valid priority values have range interval [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0].

def items is used to get all objects from the model database . You can filter which objects is you want to generate the absolute urls for setmap.

def location is used to get perticular id of object or you can take slug also for creating actual url.

def lastmod is used to set the date of last modification.

Now we need to register this sitemap.py into url

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

sitemaps = {
    'articles': ArticleSitemap
}

urlpatterns = [
     path('admin/', admin.site.urls),
     path('api/',include('api.urls')),
     path('sitemap.xml',sitemap,{'sitemaps': sitemaps}, name='sitemap'),
]

 

Finally you can migrate app to see the sitemap.xml file

py manage.py makemigrations
py manage.py migrate
py manage.py runserver

 

 

To see the sitemap.xml file go to browser and use this url

http://127.0.0.1:8000/sitemap.xml

Sitemap Created Successfully.

If you have any doubt comment below.

Author Image
Guest User

0 Comments