Creating Sitemaps in Django

Sanket Lolge   08 June,2021  

Table of Contents

  1. Introduction

  2. Types of Sitemap

    • HTML Sitemap
    • XML Sitemap

  3. Step 1: Create Virtual Environment

  4. Step 2: Create Project

  5. Step 3: Install Django

  6. Step 4:Create Application recipies

  7. Step 5: Create Model

  8. Step 6: Django Admin

  9. Step 7: Create Views

  10. Step 8: Create Template

  11. Step 9: Create URL's

  12. Step 10: Installation

 

Sitemaps are simple XML files that are used to provide details for every URL on a website. They include location, date of last modification, change frequency, and page priority. If you’ve got an international site, you can also use your sitemap to note the relationship between language versions of a URL. This helps search engines to learn about the site’s structure and index your website.

Today, the site map has become one of the most important SEO criteria to be found on every site.

A sitemap is also used to tell the following information about the pages:

  1. How frequently the page changes.
  2. Last modification date of the page.
  3. Priority of the URL in relation to other URLs.

Types of Sitemap

Sitemaps are of two types:

  1. HTML Sitemap.
  2. XML Sitemap.

HTML Sitemap

An HTML Sitemap is designed for the users to help them navigate the site. We can easily create an HTML Sitemap by simply creating a list using <ol> or <ul> tag.

For example:

<h2>The Great Django Sitemap</h2>

<ul>

<li><a href="http://gktcs.in">Home</a></li>

<li><a href="http:// gktcs.in/blog">Blog</a></li>

<li><a href="http:// gktcs.in/contact">contact</a></li>

<li><a href="http:// gktcs.in/careers">Careers</a></li>

<li><a href="http:// gktcs.in/events">Events</a></li>

</ul>

 

Remember that HTML sitemaps are for human consumption, they are not meant for search engines. For that reason, Google Webmaster Tool and others don't even allow you to submit an HTML sitemap.

XML Sitemap

XML Sitemap is the most preferred way of creating sitemaps today. Webmaster tools provided by major search engines accepts XML sitemap. Here is an example of XML sitemap:

<?xml version="1.0" encoding="UTF-8"?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

<url>

<loc>http://www.gktcs.in/home</loc>

<lastmod>2017-05-10</lastmod>

<changefreq>monthly</changefreq>

<priority>0.9</priority>

</url>

<url>

<loc>http:// www.gktcs.in/blog/</loc>

<lastmod>2017-05-10</lastmod>

<changefreq>monthly</changefreq>

<priority>0.6</priority>

</url>

<url>

<loc>http:// www.gktcs.in/contact/</loc>

<lastmod>2017-05-10</lastmod>

<changefreq>monthly</changefreq>

<priority>0.6</priority>

</url>

</urlset>

 

Generally, a sitemap exists at a single location as a sitemap.xml file such as https://gktcs.in/sitemap.xml. But for sites with over 50,000 URLs, a sitemap index, which creates multiple sitemap files, is appropriate.

Step 1: Create Virtual Environment

Before we can generate a sitemap, we need a basic Django website!. Let's create a recipes app for this purpose.

On the command line, install Django, create a new project called config, and a new app called recipes.

First, create folder Recipes and enter into the folder

$ mkdir Recipes && cd Recipes

Create Virtual Environment  for our project

$ virtualenv ENV


Then activate that environment using the following command

$ source ENV/bin/activate

Step 2: Create Project

The next step is to create a project

$ django-admin.py startproject config

$ cd config

Step 3: Install Django

Install Django in our project environment

$ pip install django

Step 4:Create Application recipies

Create recipes application in config project

$ python manage.py startapp recipes

Then within the config/settings.py file add our new recipes app.

# config/settings.py

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'recipes', # new

]

 

Run the first migrate command to initialize the database.

(recipes) $ python manage.py migrate

Step 5: Create Model

Our model will contain a title and description for each recipe. We'll also add str and get_absolute_url methods as well.

# recipes/models.py

from django.db import models

from django.urls import reverse

class Recipe(models.Model):

        title = models.CharField(max_length=50)

        description = models.TextField()

        def __str__(self):

                return self.title

        def get_absolute_url(self):

                return reverse('recipe_detail', args=[str(self.id)])

 

Now create a migrations file for this change and add it to our database via the migrate command.

(recipes) $ python manage.py makemigrations

(recipes) $ python manage.py migrate

Step 6: Django Admin

create a superuser account to log in.

(recipes) $ python manage.py createsuperuser

we also need to update recipe/admin.py to display our new app in the admin.

# recipes/admin.py

from django.contrib import admin

from .models import Recipe

class RecipeAdmin(admin.ModelAdmin):

        list_display = ('title', 'description',)

admin.site.register(Recipe, RecipeAdmin)

 

Start up the local server with the command python manage.py runserver and log in at http://127.0.0.1:8000/admin with your superuser account.

Click on the "+Add" next to the Recipe section and create two new recipes.

Now we have content. What's missing is our URL paths, views, and templates.

Step 7: Create Views

We will use the built-in Generic Class-Based Views for list and detail pages.

# recipes/views.py

from django.views.generic import ListView, DetailView

from .models import Recipe

 

class RecipeListView(ListView):

        model = Recipe

        template_name = 'recipe_list.html'

 

class RecipeDetailView(DetailView):

        model = Recipe

        template_name = 'recipe_detail.html'

 

Step 8: Create Template

First, create the blank HTML files.

(recipes) $ mkdir recipe/templates

(recipes) $ touch recipe/templates/recipe_list.html

(recipes) $ touch reciple/templates/recipe_detail.html

 

The recipe_list.html page displays all recipes.

<!-- recipe_list.html -->

<h1>Recipes</h1>

<ul>

        {% for recipe in object_list %}

                <li><a href="{{ recipe.get_absolute_url }}">{{ recipe.title }}</a></li>

        {% endfor %}        

</ul>

 

<!-- recipe_detail.html -->

<div>

    <h2>{{ object.title }}</h2>

    <p>{{ object.description }}</p>

</div>

 

Step 9: Create URLs

There are two URL files to update: our top-level one at config/urls.py and then one within the recipes app that must be created. Let's create that new one now.

(recipes) $ touch recipes/urls.py

Now update config/urls.py

# config/urls.py

from django.contrib import admin

from django.urls import path, include # new

 

urlpatterns = [

        path('admin/', admin.site.urls),

        path('', include('recipes.urls')), # new

]

 

And then recipes/urls.py

# recipes/urls.py

from django.urls import path

from .views import RecipeListView, RecipeDetailView

urlpatterns = [

        path('<int:pk>', RecipeDetailView.as_view(), name='recipe_detail'),

        path('', RecipeListView.as_view(), name='recipe_list'),

]

 

Now we have 3 pages in our basic app: - homepage with all recipes - a detail page for each of our 2 recipes in the database

 

 

What we want is a sitemap now!

Step 10: Installation

To add a sitemap, we must install the sitemap app to our project as well as the sites framework which it relies upon.

# config/settings.py

INSTALLED_APPS = [

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    'django.contrib.sites', # new

    'django.contrib.sitemaps', # new

    'recipes',

]

SITE_ID = 1 # new

 

The sites framework requires an update to our database so run migrate at this time.

(recipes) $ python manage.py migrate

There are several ways to implement sitemaps, but the simplest approach is to use GenericSitemap, a convenience class that covers common sitemap usage. Here's how to add it to our config/urls.py file.

# config/urls.py

from django.contrib import admin

from django.contrib.sitemaps import GenericSitemap # new

from django.contrib.sitemaps.views import sitemap # new

from django.urls import path, include

from recipes.models import Recipe # new

 

info_dict = {

        'queryset': Recipe.objects.all(),

}

urlpatterns = [

        path('admin/', admin.site.urls),

        path('', include('recipes.urls')),

        path('sitemap.xml', sitemap, # new

                {'sitemaps': {'blog': GenericSitemap(info_dict, priority=0.6)}},

                 name='django.contrib.sitemaps.views.sitemap'),

Step 11 : Run server

Make sure the server is running and visit http://127.0.0.1:8000/sitemap.xml

There's our sitemap! But notice that it's using example.com as the name of our site. This comes from the sites framework. If you go into the Django admin, there's a new section called Sites where you can change the name.

It's also possible to change the priority and changefreq. And while you might notice that the current version uses http rather than https, if your production site uses https then that will be reflected in the sitemap. Or you can change the protocol entirely, if so desired.

0
Like