Django Subdomains to do advanced things

Reading Time : ~ .

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.

    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Multifactor Authentication with Django MFA using Google Authenticator Vinisha Naladala

Use Django Multi-Factor Authentication method to verify user identity with more than one authentication methods. It can be used for user login, any transactional methods ...

Continue Reading...
Django - Template language Intro Nikhila Mergu

We can write the required logics based on programming[python] syntax in models and views but, when we want to write simple logics we should follow ...

Continue Reading...
Custom validations for serializer fields Django Rest Framework Nikhila Mergu

we can write custom validations for serializer fields in Django Rest Framework. Validators are used to validate the data whether it is semantically valid or ...

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties