Getting Started with Django Hosts
If you've ever wanted to serve different Django apps on different subdomains — like blog.example.com and wedding.example.com — then django-hosts is the package you need. Here's how I set it up for this site.
Why Subdomains?
Subdomains let you logically separate different parts of your application while keeping everything under one Django project. Each subdomain can have its own URL configuration, templates, and even its own visual identity.
Setup in 3 Steps
Install the package
pip install django-hosts
Add 'django_hosts' to your INSTALLED_APPS and configure the middleware.
Create a hosts.py file
This file maps subdomain patterns to URL configurations:
from django_hosts import patterns, host
host_patterns = patterns('',
host(r'', 'myporto.urls', name='root'),
host(r'blog', 'blog.urls', name='blog'),
host(r'wedding', 'wedding.urls', name='wedding'),
)
Configure your settings
Point Django to your hosts file and set the default host:
ROOT_HOSTCONF = 'myproject.hosts'
DEFAULT_HOST = 'root'
Gotchas I Ran Into
- Local development requires editing your
/etc/hostsfile to test subdomains - Make sure the
django_hostsmiddleware is placed before the common middleware - CSRF and allowed hosts settings need to account for all your subdomains
Once everything is wired up, it's a clean way to organize a multi-app Django project. Highly recommended if your project is growing beyond a single domain.