以下是在我的网站中为我的一个应用“博客”创建站点地图的代码:(使用Django 2.0)
settings.py
INSTALLED_APPS += [
'django.contrib.sites',
'django.contrib.sitemaps',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Run Code Online (Sandbox Code Playgroud)
urls.py
from django.urls import include, path
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import PostSiteMap
sitemaps = {'posts': PostSiteMap}
urlpatterns += [
path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap')
]
Run Code Online (Sandbox Code Playgroud)
sitempas.py(在“博客”应用目录下)
from django.contrib.sitemaps import Sitemap
from .models import Post
class PostSiteMap(Sitemap):
changefreq = 'weekly'
priority = 0.5
def items(self):
return Post.published.all()
def lastmod(self, obj):
return obj.publish
Run Code Online (Sandbox Code Playgroud)
sitemap.xml不会出现:http : //127.0.0.1 : 8000/ sitemap.xml/

有与我输入的网址匹配的网址(第八个网址)。为什么说“不匹配”?
您的代码很好,您的环境出了问题(也许您正在使用默认的Django网站,即www.example.com)。将其更改为本地环境(典型的127.0.0.1:8000)。
要在Django中执行此操作,您需要执行以下操作:
python manage.py runserver。http://127.0.0.1:8000/admin/sites/site/example.com为127.0.0.1:8000。这需要在域和显示名称中完成(当您不在生产环境中时)。F5在浏览器中按本地网页。http://127.0.0.1:8000/sitemap.xml)