Implementing Dynamic Subdomains in Django
Last Updated :
16 Jul, 2024
We are going to implement Dynamic Subdomains in Django using the Django-hosts module starting from creating a Django application. This article covers creating a Django project, a Django app, and configuring hosts to implement dynamic subdomains.
What is a Subdomain?
A subdomain is a prefix added to a domain name to separate a section of your website. Site owners primarily use subdomains to manage extensive sections that require their own content hierarchy, such as online stores, blogs, job boards, or support platforms. Subdomains function as a separate website from its domain. -WixBlog
When we are working on large web applications, we need to maintain the web pages in a hierarchical and categorical order. Django provides a URL routing system that handles this functionality out of the box. However, the built-in url routing system does not provide a straightforward way to manage dynamic subdomains. In this article, we will explore how to setup dynamic sub domains in Django using the Django-hosts package.
Implementing Dynamic Subdomains in Django
First, we need to install django and django-hosts:
> pip install django django-hosts
Installing Django and django-hostsNext, we will create a django application.
> django-admin startproject project_name
> cd project_name
> python manage.py startapp app_name
Initialising Django applicationNow open `settings.py` and perform following changes:
- Add `app_name` and `django_hosts` to INSTALLED_APPS
- Write 'django_hosts.middleware.HostsRequestMiddleware' and 'django_hosts.middleware.HostsResponseMiddleware' middlewares in MIDDLEWARE. Don't miss out on the order; see following image for reference. Newly added middlewares should be first and last.
- Now add two variables ROOT_HOSTCONF and DEFAULT_HOST with values "project_name.hosts" and "www," respectively.
Python
INSTALLED_APPS = [
'........',
'app_name',
'django_hosts',
]
MIDDLEWARE = [
'django_hosts.middleware.HostsRequestMiddleware',
'.......',
'django_hosts.middleware.HostsResponseMiddleware',
]
ROOT_HOSTCONF = 'project_name.hosts'
DEFAULT_HOST = 'www'
Code Snippet Explaination:
- Adding 'app_name' and 'django_hosts' to INSTALLED_APPS will bind those Django application with the 'project_name' and will allow to inherit common settings and serving templates and all.
- By adding those middlewares up and down is required to override default django middle wares and use django-hosts middleware instead.
- The ROOT_HOSTCONF variable holds the path of hosts module, where we specify our sub-domains. And the DEFAULT_HOST variable is required to specify the default sub-domain which can be expected as 'www'.
Updated Settings.pyConfiguring Hosts
Now create a new file named `hosts.py` at the location of `settings.py`. And we are ready to configure our sub domain hosts for our project.
In this `hosts.py` file, we can write as many subdomains as we need and map the respective app urls to the subdomain. Now we will create a `urls.py` file in app_name folder to manage all the urls of the application under a sub domain.
Try to make following changes in the respective files:
project_name/hosts.py:
Python
from django_hosts import patterns, host
from django.conf import settings
host_patterns = patterns('',
host('localhost:8000', settings.ROOT_URLCONF, name='www'),
host('sub-domain.localhost:8000',
'app_name.urls', name='sub_domain'),
)
project_name/urls.py
Python
from django.contrib import admin
from django.urls import path
from app_name.views import home
urlpatterns = [
path('admin/', admin.site.urls),
path('home', home, name='home'),
]
Code Snippet Explaination:
- The pattern function helps to recognise sub-domain from our URL, where the host function will convert the given arguments into Django understandable hosts to serve.
- The first pattern empty string will match with the DEFAULT_HOST('www')
app_name/views.py
Python
from django.shortcuts import HttpResponse
def home(request):
return HttpResponse("Response from main page.")
def sub_home(request):
return HttpResponse("Response from Sub Domianed page.")
app_name/urls.py
Python
from django.urls import path
from app_name.views import sub_home
urlpatterns = [
path('home', sub_home, name='sub_home'),
]
Now it is time to test our application. Start your django server with command `python manage.py runserver` and visit 'localhost:8000/home' and'sub'-domain.localhost:8000/home'.
Now we could see how the pages of two different apps are rendered in Django.
Additional Tip
When we need to specify the URL of a host in the template of another host, use the following DTL URL syntax:
<a href="{% host_url 'url_name' host 'host_name' %}" > Hyper Text </a>
Similar Reads
Python | Uploading images in Django Prerequisite - Introduction to DjangoUploading and managing image files is a common feature in many web applications, such as user profile pictures, product images, or photo galleries. In Django, you can handle image uploads easily using the ImageField in models.In this article, weâll walk through a
3 min read
Subdomain in Flask | Python Prerequisite: Introduction to Flask In this article, we will learn how to setup subdomains in Flask. But first, let's go through the basic like what is DNS and subdomains. Domain Name System (DNS): The Domain Name System (DNS) is a hierarchical and decentralized naming system for computers, services
3 min read
How to Make a Subdomain Scanner in Python? In this article, we are going to scan the subdomains using requests module in Python, which allows us to easily make HTTPS requests to get information from the websites. To install the requests module, write the following command in your command prompt. pip install requests The URL (Uniform Resource
6 min read
Knock - Subdomain Scanner Tool in Kali Linux Knock is a tool written in Python and is designed to enumerate subdomains in a target domain through a wordlist. Installation: First clone the tool from the GitHub repository by using the below command. git clone https://github.com/santiko/KnockPy.git Then Change to your preferred directory. cd Knoc
1 min read
Django settings file - step by step Explanation Once we create the Django project, it comes with a predefined Directory structure having the following files with each file having its own uses. Let's take an example // Create a Django Project "mysite" django-admin startproject mysite cd /pathTo/mysite // Create a Django app "polls" inside project
3 min read