Render XML Sitemap from Django View

1k Views Asked by At

The following code in a Django view:

def sitemap(request):
    return render(request, 'sitemap.xml', content_type = 'text/xml')

yields the following error:

Exception Type: UnicodeDecodeError Exception Value:
'utf8' codec can't decode byte 0xff in position 0: invalid start byte

How can I resolve this? All I'm trying to do is to render an XML sitemap. Any help would be appreciated. Thanks.

1

There are 1 best solutions below

1
On

Django support built-in sitemap,here is a demo:

common/sitemaps.py

from django.contrib.sitemaps import Sitemap
from django.urls import reverse_lazy

from news.models import News


class StaticViewSitemap(Sitemap):
    priority = 0.5
    changefreq = 'weekly'

    def items(self):
        return ['index', 'news_index', 'version', 'rss']

    def location(self, item):
        return reverse_lazy(item)


class NewsSitemap(Sitemap):
    priority = 0.5
    changefreq = 'weekly'

    def items(self):
        return News.objects.all().order_by('-id')

    def location(self, item):
        return reverse_lazy('news_detail', kwargs={'pk': item.id})


sitemaps = {
    'static': StaticViewSitemap,
    'news': NewsSitemap,
}

your peoject main url.py:

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

urlpatterns = [
    url(r'^$', IndexView.as_view(), name='index'),
    url(r'^admin/', admin.site.urls),
    url(r'^news/', include('news.urls')),
    url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='sitemap')
]

doc is here.