今天发现百度站长平台提交需要一个站点地图,百度了一堆都过期的,现在记录下详细过程。
1、在setting.py的INSTALL中加入Django自带的站点地图包模块

2、在setting.py的TEMPLATES中加入APP_DIRS:True

3、在项目里新建一个文件夹加入__init__.py 设置为包,然后新建个模块,名字随意我的是BlogSitemap.py

4、在BlogSitemap.py模块中加入生成站点地图的代码 如下:
from thrones.apps.blog.models import Article
from django.contrib.sitemaps import Sitemap
from django.db.models import Sum
class BlogSitemap(Sitemap):
changefreq = "daily"
#priority = 0.5
def items(self):
return Article.objects.filter(status="published")
def lastmod(self, obj):
if obj.updated:
return obj.updated
return obj.date_publish
def priority(self, obj):
if obj.views:
allReadCount = Article.objects.all().aggregate(Sum('views'))['views__sum']
curPriority = obj.views / float(allReadCount)
return '%.2f' % (curPriority / 2.0 + 0.5)
return 0.50
解释一下 changefreq更新频率。def item 这个函数必须有,是站点地图生成的数据来源,def lastmod 是排序,返回类型必须是datatime、def priority 是权重,这里用了个不想多说的算法,嘿嘿
当然还有def location的方法我没有覆盖,这里是获取xml文章的地址,没有覆盖 会默认调用get_absolute_url,如果 你的model中没有,要自己写返回文章的url
5、打开urls.py 路由配置文件。加入如下字典:

7、在urls.py文件加入路由转发

url(r'^blog_sitemap\.xml$', sitemap, {'sitemaps': blog_sitemap},
name='django.contrib.sitemaps.views.sitemap'),
8、然后就可以访问http://127.0.0.1:8000/blog_sitemap.xml 获取到站点地图的xml了
如下:

网友评论