Change SITE_ID on the fly in django
October 5, 2009 | frameworks, pythonauthor: Karol Zielinski | comments: 6 | views: 659
Tags: django, internalization, middleware, python, translate
I need dynamic SITE_ID in one of my websites (tspot), because of different domains and languages in it. I don’t want more threads, I just want to have different SITE_ID for different domains.
So… I need to create custom middleware.
Let’s do it.
cd /home/workspace/tspot mkdir middleware cd middleware vim SiteIdOnFlyMiddleware.py
and add there:
from django.conf import settings
class SiteIdOnFlyMiddleware:
def process_request(self, request):
host = request.META.get('HTTP_HOST')
if 'en.tspot.pl' in host:
settings.SITE_ID = 2
else:
settings.SITE_ID = 1
now we need to add this middleware to our settings.py
cd .. vim settings.py
and add ‘tspot.middleware.SiteIdOnFlyMiddleware.SiteIdOnFlyMiddleware’, to MIDDLEWARE_CLASSES
so it should looks like:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'tspot.middleware.SiteIdOnFlyMiddleware.SiteIdOnFlyMiddleware',
'django.middleware.locale.LocaleMiddleware',
)
now restart an app.
That’s all.
Hello, I'm Karol Zielinski, internet evangelist, an entrepreneur, project manager and a web developer from Gdynia, Poland. I like creative design, good advertisement, social media and all kind of stuff around the web.
October 18, 2009, 11:36 am
HAROSHHHHHH. EBANKO
January 28, 2010, 2:53 pm
This doesn’t work with the CurrentSiteManager.
January 29, 2010, 2:09 am
@mike
what do you mean by that?
January 29, 2010, 5:18 am
Ok, my middleware is:
class SiteResolutionMiddleware(object):
def process_request(self, request):
site_id = request.session.get(“site_id”, -1)
if site_id == -1 or settings.SITE_ID == -1:
request.session["site_id"] = 2
settings.SITE_ID = 2
I set SITE_ID to -1 in settings.py.
I create an object with site_id=2 but when I do:
object_list = MyObject.on_site.all()
It’s empty. settings.SITE_ID is still -1.
Cheers
mike
February 7, 2010, 2:00 am
This is limit Django. All standart component don`t work this Middleware.
March 8, 2010, 12:23 am
first of all, u cant change django`s settings on the fly. u must use threading, all django`s things will work, but its threads….
or u can use smthng like request.SITE_ID for each request.