标签:
Django中自带了sitemap框架,用来生成xml文件
Django sitemap演示:
sitemap很重要,可以用来通知搜索引擎页面的地址,页面的重要性,帮助站点得到比较好的收录。
开启sitemap功能的步骤
settings.py文件中django.contrib.sitemaps和django.contrib.sites要在INSTALL_APPS中
INSTALLED_APPS = (
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘django.contrib.sites‘,
‘django.contrib.sitemaps‘,
‘django.contrib.redirects‘,
#####
#othther apps
#####
)
Django 1.7及以前版本:
TEMPLATE_LOADERS中要加入‘django.template.loaders.app_directories.Loader’,像这样:
TEMPLATE_LOADERS = (
‘django.template.loaders.filesystem.Loader‘,
‘django.template.loaders.app_directories.Loader‘,
)
Django 1.8及以上版本新加入了TEMPLATES设置,其中APP_DIRS要为True,比如:
# NOTICE: code for Django 1.8, not work on Django 1.7 and below
TEMPLATES = [
{
‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
‘DIRS‘: [
os.path.join(BASE_DIR,‘templates‘).replace(‘\\‘, ‘/‘),
],
‘APP_DIRS‘: True,
},
]
然后在urls.py中如下配置:
from django.conf.urls import url
from django.contrib.sitemaps import GenericSitemap
from django.contrib.sitemaps.views import sitemap
from blog.models import Entry
sitemaps = {
‘blog‘: GenericSitemap({‘queryset‘: Entry.objects.all(), ‘date_field‘: ‘pub_date‘}, priority=0.6),
# 如果还要加其它的可以模仿上面的
}
urlpatterns = [
# some generic view using info_dict
# ...
# the sitemap
url(r‘^sitemap\.xml$‘, sitemap, {‘sitemaps‘: sitemaps},
name=‘django.contrib.sitemaps.views.sitemap‘),
但是这样生成的sitemap,如果网站内容太多就很慢,很耗费资源,可以采用分页的功能:
from django.conf.urls import url
from django.contrib.sitemaps import GenericSitemap
from django.contrib.sitemaps.views import sitemap
from blog.models import Entry
from django.contrib.sitemaps import views as sitemaps_views
from django.views.decorators.cache import cache_page
sitemaps = {
‘blog‘: GenericSitemap({‘queryset‘: Entry.objects.all(), ‘date_field‘: ‘pub_date‘}, priority=0.6),
# 如果还要加其它的可以模仿上面的
}
urlpatterns = [
url(r‘^sitemap\.xml$‘,
cache_page(86400)(sitemaps_views.index),
{‘sitemaps‘: sitemaps, ‘sitemap_url_name‘: ‘sitemaps‘}),
url(r‘^sitemap-(?P<section>.+)\.xml$‘,
cache_page(86400)(sitemaps_views.sitemap),
{‘sitemaps‘: sitemaps}, name=‘sitemaps‘),
]
这样就可以看到类似如下的sitemap,如果本地测试访问http://localhost:8000/sitemap.xml
Django:之Sitemap站点地图、通用视图和上下文渲染器
标签:
原文地址:http://www.cnblogs.com/wulaoer/p/5389213.html