Django添加sitemap的方法示例
程序员文章站
2023-01-26 23:29:55
sitemap是 google 最先引入的网站地图协议,采用 xml 格式,它的作用简而言之就是优化搜索引擎的索引效率,详细的解释可以参考 。
下面介绍下如何为djang...
sitemap是 google 最先引入的网站地图协议,采用 xml 格式,它的作用简而言之就是优化搜索引擎的索引效率,详细的解释可以参考 。
下面介绍下如何为django站点添加sitemap功能。
1、启用sitemap
在django的settings.py的installed_apps中添加
'django.contrib.sites', 'django.contrib.sitemaps',
然后migrate数据库:
$ ./manage.py makemigrations $ ./manage.py migrate
登陆django后台,修改site为你django网站的域名和名称,然后在settings.py中加入site_id = 1来制定当前的站点。
2、添加sitemap功能
(1)创建sitemap
创建sitemap.py.内容类似下面的代码:
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配置
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'),
至此,全部完成,运行你的django程序,浏览器输入:http://127.0.0.1:8000/sitemap.xml
就可以看见已经成功生成了,然后就可以提交这个地址给搜索引擎。 我的网站的sitemap的地址是:https://www.fkomm.cn/sitemap.xml
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。