1

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

Ujjwal Singh Baghel
  • 393
  • 2
  • 6
  • 23
  • Do you have any `sitemap.xml` file in your templates? Also, I don't like the `/` at the end of the URL `^sitemap\.xml/$`, why don't you use `path` like in Django's examples? – Davit Tovmasyan Oct 14 '19 at 11:21
  • No, I don't have any file named `sitemap.xml`. Well, I will remove the trailing `/` but it doesn't matter regarding the solution I guess. – Ujjwal Singh Baghel Oct 14 '19 at 11:27
  • Yes, it was en extra suggestion. The error says that there is something above the XML declaration line, which is not correct for some browsers(check with curl and see what's in the first line of the response). If you are using Django's default template then there should be a middleware or something else that adds something to the beginning of the response. – Davit Tovmasyan Oct 14 '19 at 11:33
  • Maybe some other third-party package has a template with `sitemap.xml` name. – Davit Tovmasyan Oct 14 '19 at 11:34

1 Answers1

1

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')
burning
  • 2,426
  • 6
  • 25
  • 38