温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Django中添加sitemap

发布时间:2021-04-07 17:01:17 来源:亿速云 阅读:134 作者:Leah 栏目:开发技术

本篇文章为大家展示了如何在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中添加sitemap,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI