在“Django实用攻略(三)”中,介绍了sitemap的配置。但这只能生成标准的sitemap.xml,适合google的收录。经过几次尝试,找到了自定义sitemap的方法。本文对自定义sitemap的方法,以及对django的新认知,进行介绍。
之前介绍过sitemaps这个模块的使用。今天为了自定义sitemap,看了一下这个模块的代码。实际上,这个模块,和通过startapp命令建立的模块,结构是一样的。知道了这个,用起来就没有任何障碍了。
通过python/python3命令行,查找django模块文件位置。
//进入python3命令行
$ python3
//导入django模块
>>> import django
//查看模块位置
>>> django.__file__
'/usr/local/lib/python3.7/site-packages/django/__init__.py'
如上,在django文件夹中找到contrib/sitemaps/templates/sitemap.xml,复制到自己博客的模板中,并改一个名字,例如sitemap_baidu.xml
。
修改如下
// sitemap_baidu.xml
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"{% if urlset.0.mobile %} xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/" {% endif %}>
{% spaceless %}
{% for url in urlset %}
<url>
<loc>{{ url.location }}</loc>
{% if url.mobile %}<mobile:mobile type="{{ url.mobile }}"/>{% endif %}
{% if url.lastmod %}<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>{% endif %}
{% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %}
{% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %}
</url>
{% endfor %}
{% endspaceless %}
</urlset>
修改之前用到的sitemap.py,重载Sitemap的get_urls
方法
from django.contrib.sitemaps import Sitemap
from base.models import Article
from django.contrib.sitemaps import GenericSitemap
from django.urls import reverse
import time
import datetime
class StaticViewSitemap(Sitemap):
priority = 1
changefreq = 'daily'
def items(self):
return ['index', ]
def location(self, item):
return reverse(item)
//看这里,增加一个mobile字段,按照自己页面的情况,选择htmladapt/mobile/pc。
def get_urls(self, page=1, site=None, protocol=None):
urls = super().get_urls(page, site, protocol)
for url in urls:
url['mobile'] = 'htmladapt'
return urls
class ArticleSiteMap(Sitemap):
changefreq = "daily"
priority = 0.9
def items(self):
return Article.objects.filter(state='1')
def lastmod(self, obj):
return datetime.datetime.fromtimestamp(obj.publish_date)
def location(self, obj):
return reverse('article_name', kwargs={'title': obj.seo_link})
def get_urls(self, page=1, site=None, protocol=None):
urls = super().get_urls(page, site, protocol)
for url in urls:
url['mobile'] = 'htmladapt'
return urls
最后增加一个url规则。
# urls.py
urlpatterns = [
...
# 上面是其他url配置
url('sitemap_baidu.xml', sitemap, {'sitemaps': sitemaps,'template_name':'sitemap_baidu.xml'}, name='django.contrib.sitemaps.views.sitemap'),
]