Login

Subdomain Middleware

Author:
xhenxhe
Posted:
October 9, 2008
Language:
Python
Version:
1.0
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 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.

#

Please login first before commenting.