A site map is a list of a website's content designed to help both users and search engines navigate the site.
A site map can be a hierarchical list of pages, an organization chart, or an XML document that provides instructions to search engine crawl bots.
sitemap.py
in your app.
Create two different classes in sitemap.py
file, one for static pages and another for Dynamic URLs.
Let's assume your website sell some product where product details are stored in the database. Once a new product is added to the database, you want that product page to be searchable by search engines. We need to add all such product pages/URLs to sitemaps.
StaticSitemap
in your sitemap.py
file. Define the mandatory function items in it which will return the list of objects. These objects will be passed to the location method which will create URL from these objects.
from django.contrib.sitemaps import Sitemap from django.core.urlresolvers import reverse class StaticSitemap(Sitemap): def items(self): return [ 'myapp:terms_and_conditions', 'myapp:contact_us', 'myapp:about_us' ] def location(self, item): return reverse(item)
Here in items function, we are returning appname:url_name
which will be used by location method to convert into an absolute URL.
Refer you app's urls.py
file for URL names.
from mystore.models import ProductDetailsModel class ProductSitemap(Sitemap): def items(self): return ProductDetailsModel.objects.all() def location(self, item): return reverse('myapp:product', args=[item.product_id])
Here we are getting all products from the database and generating URLs like http:example.com/product/12
.
from mystore.sitemap import StaticSitemap, ProductSitemap from django.contrib.sitemaps.views import sitemap sitemaps = { 'pages': StaticSitemap, 'products': ProductSitemap, } urlpatterns += [ url(r'^sitemap.xml$', sitemap, {'sitemaps': sitemaps}) ]
Now reload your server and go to localhost:8000/sitemap.xml
and you will be able to see your sitemap there.
Reference :
https://docs.djangoproject.com/en/2.0/ref/contrib/sitemaps/
Host your Django App for Free.