How to test sub-domains locally with django (on Linux or Mac) ?

Published: September 26, 2022

Tags: Django; Apple Mac;

DMCA.com Protection Status

Examples of how to test sub-domains locally with django:

Table of contents

Edit hosts file

By default to test locally a django app, it is possible to run a server

python manage.py runserver

and to go to the url

localhost:8000

Now, we want to test sub-domains, for example :

www.localhost:8000
fr.localhost:8000
es.localhost:8000
.
.
.

To do that open the hosts file locatedin the etc folder:

vi /etc/hosts

gives for example:

  ##
  # Host Database
  #
  # localhost is used to configure the loopback interface
  # when the system is booting.  Do not change this entry.
  ##
  127.0.0.1       localhost
  255.255.255.255 broadcasthost
  ::1             localhost
  # Added by Docker Desktop
  # To allow the same kube context to work on the host and the container:
  127.0.0.1 kubernetes.docker.internal
  # End of section

To test sub-domains locally just replace the line

127.0.0.1       localhost

by

127.0.0.1       www.localhost fr.localhost

now with

python manage.py runserver

it is possible to use the url

www.localhost:8000

or

fr.localhost:8000

Bonus

Extract sub-domain name in a Django view:

            full_url = request.build_absolute_uri()
            dn = full_url.split('/')[2]
            subdomain = dn.split('.')[0]

Implement a redirection from www to fr or vice versa

            if subdomain == 'www':
                if article.language != 'en':
                    dn_redirect = dn.replace('www',article.language)
                    full_url_redirect = full_url.replace(dn,dn_redirect)
                    response = HttpResponse(status=301)
                    response['Location'] = full_url_redirect
                    return response
            else:
                if article.language == 'en':
                    dn_redirect = dn.replace(subdomain,'www')
                    full_url_redirect = full_url.replace(dn,dn_redirect)
                    response = HttpResponse(status=301)
                    response['Location'] = full_url_redirect
                    return response

References