Login

Subdomain Middleware

Author:
xhenxhe
Posted:
October 9, 2008
Language:
Python
Version:
1.0
Tags:
middleware subdomain
Score:
7 (after 7 ratings)

This snippet will add the subdomain and domain to the request object for use in your views.

 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 6 years, 2 months ago
  2. Hours of Operation Middleware by andrew 7 years, 5 months ago
  3. GlobalRequest middleware by myq 3 years, 9 months ago
  4. middleware to capture doesnot exists exception by vbachu 3 years, 1 month ago
  5. NoDoubleSlashes middleware by simon 8 years, 7 months ago

Comments

claudep (on March 18, 2009):
<p>This is useful, thanks. </p> <p>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.</p>

#

xhenxhe (on April 3, 2009):
<p>Thanks. I've updated the snippet.</p>

#

panchicore (on November 17, 2010):
<p>usefull. more intuitive than django-subdomains app.</p>

#

Please login first before commenting.