Django添加sitemap的方法示例

yipeiwu_com5年前Python基础

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

解决python执行不输出系统命令弹框的问题

最近做一个的GUI,因为调用了os模块里的system方法,使用pyinstaller打包的时候选择不输出系统命令弹框,程序无法运行,要求要有系统命令框。在网上找到一个解决办法。使用su...

python 批量修改/替换数据的实例

在进行数据操作时,经常会根据条件批量的修改数据,如以下数据,按照日期的条件,将部门日期下的promotion改为1 tot_qty...

Centos下实现安装Python3.6和Python2共存

写在前面 centos6.8中默认自带的python版本为python2.6,那么这里需要将其改为python3 下载并解压 官方下载地址为 https://www.python.o...

Python中matplotlib中文乱码解决办法

Python中matplotlib中文乱码解决办法

Matplotlib是Python的一个很好的绘图包,但是其本身并不支持中文(貌似其默认配置中没有中文字体),所以如果绘图中出现了中文,就会出现乱码。 matplotlib绘制图像有中文...

linux系统使用python获取内存使用信息脚本分享

linux系统使用python获取内存使用信息脚本分享

复制代码 代码如下:#!/usr/bin/env Python from __future__ import print_functionfrom collections import...