djangodjango-modelsdjango-sitesdjango-sitemaps

Django Sitemaps : Get only pages of the current website


I would like to create a Site specific Sitemap using Django Sitemaps.

My idea was to do something like this :

def items(self):
    current_site = Site.objects.get_current(self.request)
    return current_site.pages.filter(draft=False)

But I have two issues :

  1. self.request is not defined, is there a way to get the real current_site inside the Sitemap ?
  2. The items URL is not right, it should starts with the right current_site

I guess, I have to pass directly the right queryset to my Sitemap, but how can I do that ?

Thanks,

Rémy


Solution

  • You can pass the site specific queryset by this way.

    def items(self):   
      return YourModel.objects.by_site()
    

    by_site is YourModel's manager function,

    def by_site(self, site=None, **kwargs):
        """Get all pages for this site"""
        if not site:
            site = Site.objects.get_current()
    
        site = site.id
    
        return self.filter(site__id__exact = site, **kwargs)