djangopython-3.xsitemapdjango-2.2django-sitemaps

Django sitemaps: XML declaration allowed only at the start of the document


I have been working on the implementation of the sitemaps on Django-2.2 for the Blog website.

The code structure I followed was-

Sitemaps.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

I guess that was pretty much it as I referenced so many links. but when I open 127.0.0.1:8000/sitemap.xml It gives me th following error-

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.

That's it, nothing on the server log. Please, If anyone can please help me out. Thanks in advance


Solution

  • Your xml document has new line in the beginning. This is the main reason you are getting this issue.

    Please change your urls.py file as per document.

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

    Your url should look like below.

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