How to add Django sitemap for search engines.



What do we mean by sitemap and how it is useful? Basically a sitemap is nothing but an XML file in your website which contains the list of all the urls that tells search-engine indexers how frequently your pages or models change. This information helps search engines index your site. In sitemaps we can also define how frequently our page changes which helps search engines to crawl through the page when the change is available and they can index the page accordingly. We can also define the priority of a page over the other pages in the website.

Here we are mentioning the steps to add sitemaps to your django website.

 

Step 1: First thing we have to do is to install sitemaps in our project which we can do by adding below code in INSTALLED_APPS of settings.py

'django.contrib.sitemaps'

 

Step 2: Create a sitemaps.py file in your project (in this example we have created this file in the folder where setting.py file is available) and add below code in it

from django.contrib.sitemaps import Sitemap

from django.urls import reverse

from blogs.models import Blogs

 

class BlogSitemap(Sitemap):

    changefreq = "daily"

    priority = 0.5

 

    def items(self):

        return Blogs.objects.all()

 

    def location(self, item):

        return reverse('detail',args=[item.slug])

 

Note: if you are using get_absolute_url() in models.py file in blogs then you can skip defined location function in above code.

 

Step 3: go yo your main urls.py file and add below codes in it

from django.contrib import admin

from django.urls import path,include

from django.contrib.sitemaps.views import sitemap

from .sitemaps import BlogSitemap

 

sitemaps = {

    'blogsitemap': BlogSitemap,

}

 

urlpatterns = [

    path('sitemap.xml', sitemap, {'sitemaps': sitemaps}),

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

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

]

 

Now go to http://127.0.0.1:8000/sitemap.xml , you will find that the urls for all the blogs available in your Blogs model are listed in this xml file.

Put your questions in comment, we will be happy to help you. Thank you!


Published : July 11, 2020