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:8000fr.localhost:8000es.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 localhost255.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_redirectreturn responseelse: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_redirectreturn response
References
| Links | Site |
|---|---|
| How to test sub-domains on my localhost on a mac? | stackoverflow |
| How to get the current URL within a Django template? | stackoverflow |
| The Ultimate Guide to Django Redirects | realpython.com |
| What Is a 301 or 302 Redirect? | domain.com |
| How to test sub-domains in my localhost? | lightrun.com |
| Testing sub-domains in my localhost using Django | stackoverflow |
