This is a very handy Django package that I’ve used in a couple of projects. Essentially django-hosts let you serve
different parts of your application under different subdomains. For example, let’s say we have a Django application
deployed on www.example.com. With this app you can serve an e-commerce under shop.example.com and the help
center under help.example.com. And in the end, it’s just a single Django website.
It can also be used to host user spaces, with a wildcard, where your users could get their own subdomain like
vitor.example.com or erica.example.com. But that require a few tweaks in the DNS configuration.
A small caveat of developing with django-hosts is that you will need to do some configurations in your local
machine, which can differ if you are using Windows, Linux or Mac.
Installation
Install it with pip:
Add the django_hosts to the INSTALLED_APPS:
Add the HostsRequestMiddleware in the beginning of the MIDDLEWARE and HostsResponseMiddleware in the end of the
MIDDLEWARE:
Still in the settings.py, add the following configuration variables:
Create a file named hosts.py right next to the urls.py:
mysite/hosts.py
Usage
Let’s create an app named help to illustrate the usage of the django-hosts:
Then inside of the new app, we create a urls.py module:
help/urls.py
Now we update the mysite/hosts, which is our ROOT_HOSTCONF:
mysite/hosts.py
Testing Locally
In order to test it locally, you will need to setup a local DNS host.
On Linux and Mac, the file is located in the path /etc/hosts. For Windows it should be somewhere in
%SystemRoot%\system32\drivers\etc\hosts.
hosts
Templates
Now instead of using the {%url'home'%} notation, you can load the django-hosts template tags:
Reverse
The django-hosts extends Django’s default reverse function so you can pass an extra argument host: