Django Add sitemap method example

  • 2020-12-07 04:06:39
  • OfStack

sitemap is the first website map protocol introduced by Google, which adopts XML format. Its function is simply to optimize the index efficiency of search engines. For detailed explanation, please refer to Baidu Encyclopedia.

Here's how to add sitemap functionality to your Django site.

1. Enable sitemap

Added to ES15en.py INSTALLED_APPS of django


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

Then migrate database:


$ ./manage.py makemigrations
$ ./manage.py migrate

Go to the Django background, change SITE to the domain name and name of your Django website, then add SITE_ID = 1 to settings.py to specify the current site.

2. Add sitemap function

(1) Create sitemap

Create sitemap. py. similar to the following code:


from django.contrib.sitemaps import Sitemap
from blog.models import Article, Category, Tag
from accounts.models import BlogUser
from django.contrib.sitemaps import GenericSitemap
from django.core.urlresolvers import reverse

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

 def items(self):
  return ['blog:index', ]

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


class ArticleSiteMap(Sitemap):
 changefreq = "monthly"
 priority = "0.6"

 def items(self):
  return Article.objects.filter(status='p')

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


class CategorySiteMap(Sitemap):
 changefreq = "Weekly"
 priority = "0.6"

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

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


class TagSiteMap(Sitemap):
 changefreq = "Weekly"
 priority = "0.3"

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

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


class UserSiteMap(Sitemap):
 changefreq = "Weekly"
 priority = "0.3"

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

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

(2) url configuration

Add url.py:


from DjangoBlog.sitemap import StaticViewSitemap, ArticleSiteMap, CategorySiteMap, TagSiteMap, UserSiteMap

sitemaps = {

 'blog': ArticleSiteMap,
 'Category': CategorySiteMap,
 'Tag': TagSiteMap,
 'User': UserSiteMap,
 'static': StaticViewSitemap
}

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

At this point, all finished, run your django application, browser input: http: / / 127.0.0.1:8000 / sitemap xml

You can see that it has been successfully generated, and then you can submit the address to the search engine. sitemap my website address is: https: / / www fkomm. cn/sitemap xml


Related articles: