By continuing to navigate on this website, you accept the use of cookies to serve you more relevant services & content.
For more information and to change the setting of cookies on your computer, please read our Cookie Policy.

Django Subdomains to do advanced things

We always struggle to give users customizations even before they log in to the system like abc.micropyramid.com and Django don't know how to handle that out of the box.

We can do it by writing simple middleware. Django Middleware has access to request and responses, so, we can get hold on to request and pass it on to Django views for further process. Here we will add a new property to request and can render pages by seeing at the subdomain property.

First, write a middleware class and include it in settings.py middlewares section.

class SimpleSubdomainMiddleware:
    def process_request(self, request):
        host = request.META.get('HTTP_HOST', '')
        host = host.replace('www.', '').split('.')
        if len(host) > 2:
            request.subdomain = ''.join(host[:-2])
        else:
            request.subdomain = None

Now you need to add it to settings.py

MIDDLEWARE_CLASSES += ( 'path_to_your_file.SimpleSubdomainMiddleware', )

Now edit your host's file to check this working. Add the following to /etc/hosts

127.0.0.1    abc.com

You can verify it by running your Django project and open xyz.abc.com in a browser to see it in action. Any view will have access to the subdomain it's serving to and you can get it by request.subdomain. Here is sample view

def login_page(request):
    if get_merchant(request.subdomain):
        render page of the get_merchant
    else:
        render generic page or redirect as you wish

This way you can render pages as per subdomains.

    Posted On
  • 05 September 2012
  • By
  • Micropyramid

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Django-REST Framework Object Level Permissions and User Level Permissions

Django-REST User Level Permissions and Object Level Permissions. User Level Permissions and Object level Permissions allow to serve customers based on their access levels or ...

Continue Reading...
What's great about Django girls to inspire women into programming

Django girls is a non-profit organization, that helps women to learn Django programming language and to inspire them into programming. They are organizing workshops all ...

Continue Reading...
How to Document API Requests using Django Rest Swagger

Django Rest Swagger is used to Document your API for eg., Listing all Your project Rest API's in the browser with brief description about the ...

Continue Reading...
open source packages

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties