1.安裝
安裝Sitemap APP的步驟如下:
- 在INSTALLED_APPS設(shè)置中添加'django.contrib.sitemaps';
- 確認(rèn)你的TEMPLATES設(shè)置中包含DjangoTemplates后端,并將APP_DIRS選項(xiàng)設(shè)置為True,當(dāng)然默認(rèn)值就是這樣,只有當(dāng)你曾經(jīng)修改過這些設(shè)置,才需要修改這個配置;
- 確認(rèn)你已經(jīng)安裝sites framework.(在INSTALLED_APPS中添加'django.contrib.sites', 并添加設(shè)置SITE_ID=1)
2.例子
假設(shè)擁有一個News模型,并且您希望Sitemap包含指向所有新聞條目的鏈接.
# sitemaps.py
from django.contrib.sitemaps import Sitemap
from myweb.models import News
from django.urls import reverse
class NewsSitemap(Sitemap):
changefreq = 'daily' # 可選,指定每個對象的更新頻率
priority = 0.6 # 可選,指定每個對象的優(yōu)先級,默認(rèn)0.5
def items(self): # 返回對象的列表.這些對象將被其他方法或?qū)傩哉{(diào)用
return News.objects.all()
def lastmod(self, obj): # 可選,該方法返回一個datetime,表示每個對象的最后修改時間
return obj.pub_time
def location(self, obj):#可選.返回每個對象的絕對路徑.如果對象有g(shù)et_absolute_url()方法,可以省略location
return reverse('new', kwargs={'new_id': obj.id})
# url.py
from django.contrib.sitemaps import sitemap # 導(dǎo)入sitemap視圖
from xxx.sitemaps import NewsSitemap
sitemaps = {
'new': NewsSitemap,
}
urlpatterns = [
...
url(r'^sitemap\.xml$', sitemap, {'sitemap': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
]
當(dāng)客服端訪問 /sitemap.xml時,這將告訴Django生成一個Sitemap.
sitemap視圖需要一個額外的必需參數(shù):{sitemaps': sitemaps}
.sitemaps
是一個字典,將小節(jié)的標(biāo)簽(例如:new或blog)映射到Sitemap類(例如:NewsSitemap).它也可以映射到Sitemap類的實(shí)例(例如: NewsSitemap(some_var)).
3.靜態(tài)視圖的Sitemap
通常焦除,您希望搜索引擎抓取工具索引既不是對象詳細(xì)信息頁面也不是列表頁的視圖(例如index頁面)压储。解決方案是在 items
中顯式列出這些視圖的網(wǎng)址名稱续搀,并在網(wǎng)站地圖的 location
方法中調(diào)用 reverse()
from django.contrib.sitemaps import Sitemap
from django.urls import reverse
class StaticViewSitmap(Sitemap):
priority = 0.7
changefreq = 'daily'
def items(self):
return ['index']
def location(self, obj):
return reverse('index')