jazzband / django-hosts

Dynamic and static host resolving for Django. Maps hostnames to URLconfs.
http://django-hosts.rtfd.org
Other
982 stars 106 forks source link

Settings depending on host #9

Closed grillermo closed 11 years ago

grillermo commented 11 years ago

Any ideas on how to import settings depending on the host? Middleware approach is a good idea?

grillermo commented 11 years ago

My solution, right below django-hosts middleware, i added this middleware:

from django.conf import settings

class Settings(object): def process_request(self,request): if 'another_domain.com' in str(request.host): settings.GOOGLE_ANALYTICS_ID = 'custom_data' settings.FACEBOOK_APP_ID = 'custom_data'

jezdez commented 11 years ago

Yep, that's how I handle it myself, too.

grillermo commented 11 years ago

Ok i have to add, that this causes problems, because you change the settings for the entire django process, so if another user comes in in one domain and you change settings, it will change also for users coming to the other domain this django app handles. I just ran into this bug in a production site :P What i had to do was add settings PER request, like so

import os
from django.conf import settings

class DumpObject: pass

class Settings(object):
    def process_request(self,request):
        # the dumpobject is here just to keep the settings.property  syntax similar, it could have been a dict
        request.settings = DumpObject()
        # and then we will update our dumpobject with the real settings
        for setting in dir(settings):
            if not setting.startswith('__'): # avoiding the internal __ properties
                setattr(request.settings, setting, getattr(settings,setting))
        if 'another_domain' in str(request.host):
            # and override the settings depending on the host, ONLY for this request
            request.settings.GOOGLE_ANALYTICS_ID = 'UA-38203365-1'

So i had to change all my code that was doing settings.property to request.settings.property. I usually only access settings on the context of a request, so this worked out pretty good for me.