Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Dynamically set SITE_ID in settings.py based on URL?

Tags:

python

django

web

What is a good way to dynamically set SITE_ID in settings.py based on domain name in URL?

I have an app that will be running with too many domain names (city based) that a custom settings.py file for each domain is just not doable.

Is there a way to set it dynamically?

like image 280
WayBehind Avatar asked Oct 30 '14 17:10

WayBehind


2 Answers

You can do a custom middleware which reads the request and sets the SITE_ID. I use this code on one of my sites:

class SiteMiddleware(object):
    def process_request(self, request):
        try:
            current_site = Site.objects.get(domain=request.get_host())
        except Site.DoesNotExist:
            current_site = Site.objects.get(id=settings.DEFAULT_SITE_ID)

        request.current_site = current_site
        settings.SITE_ID = current_site.id

You should look at Django's documentation on middleware to find out how to add your own middleware. https://docs.djangoproject.com/en/dev/topics/http/middleware/

like image 129
Pierre Drescher Avatar answered Nov 07 '22 08:11

Pierre Drescher


The middleware code form seems to have changed. The current (Django v3.1) form of the code (that seems to work):

from django.conf import settings
from django.contrib.sites.models import Site

class DynamicSiteDomainMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        try:
            current_site = Site.objects.get(domain=request.get_host())
        except Site.DoesNotExist:
            current_site = Site.objects.get(id=settings.DEFAULT_SITE_ID)

        request.current_site = current_site
        settings.SITE_ID = current_site.id


        response = self.get_response(request)
        return response
like image 28
MinchinWeb Avatar answered Nov 07 '22 10:11

MinchinWeb