django-hosts is a Django library that allows you to manage multiple subdomains within a single Django project by mapping each subdomain to its own URL configuration. This is useful for structuring apps like www.example.com, api.example.com, or admin.example.com using clean, maintainable code. In this guide, you'll learn how to install, configure, and test django-hosts in a Django project.
-
Install django-hosts:
pip install django-hosts
-
Add django_hosts to INSTALLED_APPS in settings.py:
INSTALLED_APPS = [ # other apps 'django_hosts', ]
-
Add django-hosts middleware in settings.py:
MIDDLEWARE = [ 'django_hosts.middleware.HostsRequestMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', # other middleware 'django_hosts.middleware.HostsResponseMiddleware', ]
-
Set ROOT_HOSTCONF and DEFAULT_HOST in settings.py:
ROOT_HOSTCONF = 'your_project.hosts' DEFAULT_HOST = 'www'
-
Create a hosts.py file in your project directory (next to settings.py):
from django_hosts import patterns, host host_patterns = patterns('', host(r'www', 'your_project.urls', name='www'), host(r'api', 'your_project.api_urls', name='api'), )
- Ensure urls.py and api_urls.py exist for each subdomain you reference.
-
Run the server and test your subdomains:
- http://localhost:8000/ for www
- http://api.localhost:8000/ for api (you may need to modify /etc/hosts)