Skip to content

Instantly share code, notes, and snippets.

@phpdude
Created December 4, 2011 14:15
Django subdomains Full support
Adds Django full subdomains urls upport for urlpatterns and reverse resolving.
Requires installation into settings.py
Allows you route and generate views various urls.
'''
Example:
'domain.com' -> ''
'domain.com/doc' -> 'doc'
'domain.com/doc/' -> 'doc/'
'sub.domain.com' -> '/sub/'
'sub.domain.com/doc' -> '/sub/doc'
'sub.domain.com/doc/' -> '/sub/doc/'
'domain.com/foo' -> 'foo'
'foo.domain.com' -> '/foo/'
'sub1.sub2.domain
'''
from django.core import urlresolvers
from settings import SITE_DOMAIN
__author__ = 'phpdude'
class SubdomainsMiddleware:
def process_request(self, request):
"""
Support subdomains in request, templates
"""
domain_parts = request.get_host().split(".")
if len(domain_parts) > 2:
subdomain = "_".join(domain_parts[:-2])
if subdomain.lower() in ['www']:
subdomain = ""
domain = ".".join(domain_parts[1:])
else:
subdomain = ""
domain = request.get_host()
request.subdomain = subdomain.replace("_", ".")
request.domain = domain
if subdomain:
request.path_info = "//" + subdomain + request.path_info
def subdomains_template_context(request):
"""
Populate the board in the template
"""
return {
"subdomain": request.subdomain,
"domain": request.domain
}
__real_reverse = urlresolvers.reverse
def reverse(*args, **kwargs):
url = __real_reverse(*args, **kwargs)
if url[0:2] == "//":
url = url[2:].split("/")
url = "http://" + url[0].replace("_", ".") + "." + SITE_DOMAIN + "/" + "/".join(url[1:])
return url
urlresolvers.reverse = reverse
MIDDLEWARE_CLASSES = (
....
'middleware.SubdomainsMiddleware'
)
TEMPLATE_CONTEXT_PROCESSORS = (
....
'middleware.subdomains_template_context'
)
SITE_DOMAIN = "domain.com:8000" # Requires full domain name with port if needed for runserver enviroument
# if you want your sessions working cross domain
SESSION_COOKIE_DOMAIN = '.' + SITE_DOMAIN.split(":")[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment