How to create a sitemap in Django?

1. Add ‘django.contrib.sitemaps’ to your app settings file

Add ‘django.contrib.sitemaps’ to the INSTALLED_APPS list in settings.py file.

2. Add sitemap path in your urls.py file

Open the urls.py file and add the following lines of code:

from django.contrib.sitemaps.views import sitemap
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),

3. Create the Sitemap Class

A Sitemap class represents a section of the entries in the sitemap.

For example, one Sitemap class could represent all offers in my Deal application, while another Sitemap class represents all static pages on the site, etc.

How to create a sitemap Class?

Create a new file named sitemaps.py in the main app directory and add the following code to it:

from django.contrib.sitemaps import Sitemap
from .models import ModelName

class ModelNameSitemap(Sitemap):    
    changefreq = "monthly"
    priority = 0.9

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

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

4. Make sure you define the method get_absolute_url() in your Model class

    def get_absolute_url(self):
        return '/'+self.slug 

5. Add sitemap classes in Your urls.py file

from .sitemaps import ModelNameSitemap, ShopSitemap

sitemaps = {
    'modelnames': ModelNameSitemap,
    'shops': ShopSitemap,
}

How to add homepage to the Django sitemap?

The solution is to explicitly list URL names for these static page views in items and call reverse() in the location method of the sitemap. Read here about Sitemap for static views

# sitemaps.py
from django.contrib import sitemaps
from django.core.urlresolvers import reverse

class StaticViewSitemap(sitemaps.Sitemap):
    priority = 0.5
    changefreq = 'daily'

    def items(self):
        return ['main', 'about', 'license']

    def location(self, item):
        return reverse(item)

# urls.py
from django.conf.urls import url
from django.contrib.sitemaps.views import sitemap

from .sitemaps import StaticViewSitemap
from . import views

sitemaps = {
    'static': StaticViewSitemap,
}

!!Be careful

Django 2.0 removes the django.core.urlresolvers module, which was moved to django.urls in version 1.10. You should change any import to use django.urls instead, like this:

from django.urls import reverse

#sitemaps.py
from django.urls import reverse

#for homepage
class StaticViewSitemap(Sitemap):
    priority = 1
    changefreq = 'always'

    def items(self):
        return ['home']

    def location(self, item):
        return reverse(item) 

6. Run the /sitemap.xml in your browser

Run the http://127.0.0.1:8000/sitemap.xml/ in your browser and if all is well you should see the generated XML sitemap file.


Leave a Comment

WebPedia.net