找不到页面:http://127.0.0.1:8000/sitemap.xml/

jua*_*nli 0 sitemap django

以下是在我的网站中为我的一个应用“博客”创建站点地图的代码:(使用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/ 在此处输入图片说明

在此处输入图片说明

有与我输入的网址匹配的网址(第八个网址)。为什么说“不匹配”?

Lau*_*azo 5

您的代码很好,您的环境出了问题(也许您正在使用默认的Django网站,即www.example.com)。将其更改为本地环境(典型的127.0.0.1:8000)。

要在Django中执行此操作,您需要执行以下操作:

  1. 在命令提示符下检查是否正在运行本地服务器,如果不是,请键入python manage.py runserver
  2. http://127.0.0.1:8000/admin/sites/site/
  3. 将默认站点(通常是Django中的默认站点)更改example.com127.0.0.1:8000。这需要在域和显示名称中完成(当您不在生产环境中时)。
  4. F5在浏览器中按本地网页。
  5. 转到您的站点地图页面(http://127.0.0.1:8000/sitemap.xml
  6. 和瞧!有您的站点地图。