【问题标题】:Django sitemaps: XML declaration allowed only at the start of the documentDjango 站点地图:仅在文档开头允许 XML 声明
【发布时间】:2019-10-14 10:02:52
【问题描述】:

我一直致力于在 Django-2.2 上为博客网站实施站点地图。

我遵循的代码结构是-

站点地图.py

from django.contrib.sitemaps import Sitemap
from .models import Post

class PostSitemap(Sitemap):    
    changefreq = "never"
    priority = 0.9

    def items(self):
      return Post.objects.all()

urls.py

from django.contrib.sitemaps.views import sitemap
from .sitemaps import PostSitemap

sitemaps = {
    'posts': PostSitemap
}

urlpatterns = [
    url(r'^sitemap\.xml/$', sitemap, {'sitemaps' : sitemaps } , name='sitemap'),
]

settings.py

INSTALLED_APPS = [
    ...
    'django.contrib.sites',
    'django.contrib.sitemaps',
]

SITE_ID = 1

我想大概就是这样,因为我引用了这么多链接。 但是当我打开127.0.0.1:8000/sitemap.xml 它给了我以下错误-

This page contains the following errors:
error on line 2 at column 6: XML declaration allowed only at the start of the document
Below is a rendering of the page up to the first error.

就是这样,服务器日志上没有任何内容。 请,如果有人可以请帮助我。 提前致谢

【问题讨论】:

  • 您的模板中有sitemap.xml 文件吗?另外,我不喜欢 URL ^sitemap\.xml/$ 末尾的 /,你为什么不像 Django 的示例中那样使用 path
  • 不,我没有任何名为 sitemap.xml 的文件。好吧,我将删除尾随的/,但我猜的解决方案并不重要。
  • 是的,这是额外的建议。该错误表示 XML 声明行上方有一些内容,这对于某些浏览器是不正确的(使用 curl 检查并查看响应的第一行中的内容)。如果您使用的是 Django 的默认模板,那么应该有一个中间件或其他东西可以在响应的开头添加一些内容。
  • 可能其他第三方包的模板名称为sitemap.xml

标签: django python-3.x sitemap django-2.2 django-sitemaps


【解决方案1】:

您的 xml 文档开头有新行。这是您遇到此问题的主要原因。

请根据文档更改您的 urls.py 文件。

https://docs.djangoproject.com/en/2.2/ref/contrib/sitemaps/

您的网址应如下所示。

from django.contrib.sitemaps.views import sitemap

path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
     name='django.contrib.sitemaps.views.sitemap')

【讨论】:

  • Followed- 我得到了同样的错误 & 使用 curl 命令-<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"> <url> <loc>127.0.0.1:8000</loc> </url> </urlset>
猜你喜欢
  • 1970-01-01
  • 2012-12-06
  • 2013-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多