3

I am using sites framework with RequestSite (no SITE_ID set) to generate content based on domain. I need to generate sitemaps for each domain with different results but I didnt find a way how to make this two frameworks work together. Is there any way to get Site of the current request in Sitemap? (getting it from SITE_ID config is not an option for me).

Here is an example of what I would like to do:

from django.contrib.sitemaps import Sitemap
from blog.models import Entry

class BlogSitemap(Sitemap):

    def items(self, request):
        return Entry.objects.filter(is_draft=False, site=request.site)

But its not possible because there is no request in items(). Is there any other way how to filter items in sitemap based on site?

igo
  • 6,359
  • 6
  • 42
  • 51
  • I don't get the question properly. Are you trying to get the sitemap based on the requested domain? Or you want to show some specific sitemap for domain_1 and some for domain_2? – JPG Nov 19 '19 at 14:53
  • @JPG Yes, I need specific content based on domain. See updated question – igo Nov 20 '19 at 15:11

1 Answers1

2

Try following example:


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

from blog.models import Entry


class BlogSitemap(Sitemap):
    _cached_site = None

    def items(self):
        return Entry.objects.filter(is_draft=False, site=self._cached_site)

    def get_urls(self, page=1, site=None, protocol=None):
        self._cached_site = site
        return super(BlogSitemap, self).get_urls(page=page, site=site, protocol=protocol)

And in urls.py

urlpatterns = [
    url('sitemap.xml', sitemap, {
        'sitemaps': {'blog': BlogSitemap}
    }, name='django.contrib.sitemaps.views.sitemap'),

    # ...
    # other your urls
]

This should work now. Let me know if you'll have any questions.

wowkin2
  • 5,895
  • 5
  • 23
  • 66
  • To prepare list of urls for items that will be used for sitemap. Actually weird thing, that it doesn't have this feature. – wowkin2 Nov 23 '19 at 12:52