Subdomain Middleware

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class SubdomainMiddleware:
    """ Make the subdomain publicly available to classes """
    
    def process_request(self, request):
        domain_parts = request.get_host().split('.')
        if (len(domain_parts) > 2):
            subdomain = domain_parts[0]
            if (subdomain.lower() == 'www'):
                subdomain = None
            domain = '.'.join(domain_parts[1:])
        else:
            subdomain = None
            domain = request.get_host()
        
        request.subdomain = subdomain
        request.domain = domain

More like this

  1. Ignore Csrf Middleware by coleifer 3 years, 10 months ago
  2. Hours of Operation Middleware by andrew 5 years, 1 month ago
  3. GlobalRequest middleware by myq 1 year, 4 months ago
  4. middleware to capture doesnot exists exception by vbachu 9 months, 2 weeks ago
  5. NoDoubleSlashes middleware by simon 6 years, 3 months ago

Comments

claudep (on March 18, 2009):

This is useful, thanks.

However, it might be safer to use the request get_host() method instead of META['HTTP_HOST'], because it is not guaranteed to be set. E.g. in tests, META['HTTP_HOST'] is not defined.

#

xhenxhe (on April 3, 2009):

Thanks. I've updated the snippet.

#

panchicore (on November 17, 2010):

usefull. more intuitive than django-subdomains app.

#

(Forgotten your password?)