Eliot S Winchell
Eliot S Winchell

Reputation: 368

Django Site_ID's and Sitemaps

I'm trying to setup a Sitemap for Google Search Console, and I'm having problems when it comes to setting up the Django "sites" framework. When I put "SITE_ID = 1" in my settings.py in the project settings file, I get a warning when running

python manage.py ping_google [/sitemap.xml]

as it returns "urllib2.HTTPError: HTTP Error 400: Bad Request", and the sitemap.xml doesn't generate.

# sitemaps.py
from django.contrib import sitemaps
from django.core.urlresolvers import reverse

class StaticViewSitemap(sitemaps.Sitemap):
    priority = 0.5
    changefreq = 'daily'

    def items(self):
        return ['index']

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

urls.py

from . import views
from .sitemaps import StaticViewSitemap

sitemaps = {
    'static': StaticViewSitemap,
}

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

I've added django.contrib.sitemaps and django.contrib.sites under INSTALLED_APPS. I only have one site, or "app". I'm missing something on the logic side, not sure how to define SITE_ID correctly. I get the error "no site_id defined" if I remove that SITE_ID = 1 in my project settings.py

Upvotes: 1

Views: 856

Answers (3)

Yousef Alm
Yousef Alm

Reputation: 238

If you want to run the command directly from the view:

from django.core.management import call_command

def daily_crons_view(request):
    # Ping Google
    return call_command('ping_google [/sitemap.xml]')

Upvotes: 0

Eliot S Winchell
Eliot S Winchell

Reputation: 368

I forgot to remove the square brackets in python manage.py ping_google [/sitemap.xml] which causes the command to not work.

Upvotes: 1

doniyor
doniyor

Reputation: 37934

You can try with requests, which is much easier to understand:

PING_URL = "http://www.google.com/webmasters/tools/ping"

def ping_google(sitemap_url=None, ping_url=PING_URL):
    if not sitemap_url:
        raise Exception('sitemap url must be given')

    current_site = Site.objects.get_current()
    url = "http://%s%s" % (current_site.domain, sitemap_url)
    requests.get(
        ping_url, params={'sitemap': url}   
    )

the original ping_google function lives here:

...\site-packages\django\contrib\sitemaps\__init__.py

Upvotes: 1

Related Questions