nihal111
nihal111

Reputation: 388

Django sitemap static pages

I have a website containing dynamic pages for Content which is added and removed periodically. Along with that the website also has static pages that always exist like /, /about, /how-it-works etc. I have configured my sitemaps.py file to load all the dynamic content pages in the sitemap.

sitemap.xml

...
<url>
<loc>
https://www.mywebsite.com/record?type=poem&id=165
</loc>
<changefreq>weekly</changefreq>
<priority>0.5</priority>
</url>
...

sitemaps.py

from django.contrib.sitemaps import Sitemap

from website.models import Content

class MySitemap(Sitemap):
    changefreq = "weekly"
    priority = 0.5

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

models.py

class Content(models.Model):
    content_type = models.CharField(max_length=255)
    ...
    def get_absolute_url(self):
        return '/record?type=' + self.content_type + '&id=' + str(self.id)

How do I add those static pages (/, /about etc) in my sitemap? Thanks!

Upvotes: 3

Views: 3391

Answers (1)

nihal111
nihal111

Reputation: 388

After a bit of searching I found this Django Sitemaps and "normal" views. Following along Matt Austin's answer I was able to achieve what I wanted. I'll leave what I did, here for future reference.

sitemaps.py

from django.contrib.sitemaps import Sitemap
from django.core.urlresolvers import reverse

from website.models import Content

class StaticSitemap(Sitemap):
    """Reverse 'static' views for XML sitemap."""
    changefreq = "daily"
    priority = 0.5

    def items(self):
        # Return list of url names for views to include in sitemap
        return ['landing', 'about', 'how-it-works', 'choose']

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

class DynamicSitemap(Sitemap):
    changefreq = "daily"
    priority = 0.5

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

urls.py

from website.sitemaps import StaticSitemap, DynamicSitemap
sitemaps = {'static': StaticSitemap, 'dynamic': DynamicSitemap}

urlpatterns = [
    ...
    url(r'^sitemap.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
]

Upvotes: 9

Related Questions