Django==2.2
Python==3.6
这是在 Django 中使用站点地图索引的更好更简单的方法,django.contrib.sitemaps
通过将其添加INSTALLED_APPS
到settings.py
. 在您的应用程序中编写 sitemaps.py 文件并根据需要定义类。django.contrib.sitemap.Sitemap
在站点地图类中扩展StaticViewSitemap
静态 URL 的示例,确保您的所有静态 URL 都具有用于reverse
查找的名称(从 URL 名称获取 URL)
# app/sitemap.py
from django.contrib import sitemaps
from django.urls import reverse
class StaticViewSitemap(sitemaps.Sitemap):
priority = 0.6
changefreq = 'monthly'
def items(self):
# URLs names
return ['index', 'aboutus', 'ourstory',]
def location(self, item):
return reverse(item)
在 urls.py 中导入所有站点地图导入站点地图和索引,django.contrib.sitemaps.views
然后使用站点地图创建字典
# urls.py
from django.contrib.sitemaps.views import sitemap, index
from app.sitemaps import StaticViewSitemap
# add as many as sitemap you need as one key
sitemaps = {
"static" : StaticViewSitemap,
}
urlpatterns = [
# sitemap.xml index will have all sitemap-......xmls index
path('sitemap.xml', index, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.index'),
# sitemap-<section>.xml here <section> will be replaced by the key from sitemaps dict
path('sitemap-<section>.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
]
在这里您将有两个站点地图 1. sitemaps.xml 2. sitemaps-static.xml 运行服务器打开 URL:http://localhost:8000/sitemap.xml
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>http://127.0.0.1:8000/sitemap-static.xml</loc>
</sitemap>
</sitemapindex>
Django 自动创建了站点地图索引,现在打开 URL: http: //127.0.0.1 :8000/sitemap-static.xml
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://localhost:8000/</loc>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>http://localhost:8000/about-us</loc>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>http://localhost:8000/our-story</loc>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
</urlset>