Django sitemap change base url

I am using https://docs.djangoproject.com/en/dev/ref/contrib/sitemaps/?from=olddocs .

I have a Sitemap created from api.mydomain.me for the domain: mydomain.com.

Is it possible to specify a base url with django?

Now with the return of the location () method:

api.mydomain.me/page/3123 instead of mydomain.com/page/3123

Is it possible? Thank.

+3
source share
3 answers

Solved, I redefined my own get_urls. He works:

class MySitemap(Sitemap):
    changefreq = "never"
    priority = 0.5
    location = ""

    def get_urls(self, site=None, **kwargs):
        site = Site(domain='mydomain.com', name='mydomain.com')
        return super(MySitemap, self).get_urls(site=site, **kwargs)

    def items(self):
        return MyObj.objects.all().order_by('pk')[:1000]

    def lastmod(self, obj):
        return obj.timestamp
+9
source

You can try something like this:

from django.contrib.sites.models import Site, SiteManager

def get_fake_site(self):
    return Site(domain='mydomain.com', name='mydomain.com')

SiteManager.add_to_class('get_current', get_fake_site)

You must do this before constructing the yous site map, and return it to default after it.

0
source

And if you have several Sitemaps classes, you can use the mixin approach.

Example for Django 1.5.1.

from django.contrib.sitemaps import Sitemap
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from yourapp.models import MyObj


class SiteMapDomainMixin(Sitemap):

    def get_urls(self, page=1, site=None, protocol=None):
        # give a check in https://github.com/django/django/blob/1.5.1/django/contrib/sitemaps/__init__.py
        # There also a "protocol" argument.
        fake_site = Site(domain='mydomain.com', name='mydomain.com')
        return super(SiteMapDomainMixin, self).get_urls(page, fake_site, protocol=None)


class MySitemap(SiteMapDomainMixin):
    changefreq = "never"
    priority = 0.5

    def items(self):
        return MyObj.objects.all().order_by('pk')[:1000]

    def location(self, item):
        return reverse('url_for_access_myobj', args=(item.slug,))

    def lastmod(self, obj):
        return obj.updated_at



class AnotherSitemap(Sitemap):
    changefreq = "never"
    priority = 0.5

    def items(self):
        return ['url_1', 'url_2', 'url_3',]

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

Urls.py url will look like ...

from sitemaps import MySitemap
from sitemaps import AnotherSitemap
from yourapp.views import SomeDetailMyObjView
admin.autodiscover()

sitemaps = {
    'mysitemap': MySitemap,
    'anothersitemap': AnotherSitemap,
}


urlpatterns = patterns('',
    # other urls...
    url(r'^accessing-myobj/(?P<myobj_slug>[-\w]+)$', SomeDetailMyObjView, name='url_for_access_myobj'),
    (r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)
0
source

All Articles