Part 1: Setup¶
It is assumed that you are familiar with the basic concepts of building a Django app. If not, it is recommended that you complete the Django tutorial first and then come back to this tutorial.
Also it is assumed that you have Django installed. If not, please head here first and then come back to this tutorial.
Step 1: Setting up a new project¶
Let's setup a new Django project which will be the base project that'll be used for the rest of this tutorial.
Note
If you already have a Django project, you may skip this step.
$ cd <your_project_dir>
$ <activate the virtualenv for the project>
(venv) $ django-admin startproject mt_site
This would create the following directory layout:
mt_site/
manage.py
mt_site/
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
Step 2: Setting up the database¶
Although any database that is compliant to work with the Django ORM can be used, we'll be using PostgreSQL for the purposes of this tutorial.
Refer to this link for the installation procedure specific to your platform.
Once done, create a database named tenant_1
inside this running PostgreSQL server.
The psycopg2
DB adapter would be required for Django to communicate with this database. Refer to
this link for installation instructions.
Once done, configure the DATABASES
dictionary with the appropriate details as follows:
# mt_site/settings.py
# Assuming your database runs on 127.0.0.1:5432
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'tenant_1',
'USER': 'your_db_user',
'PASSWORD': 'your_db_password',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
...
Note
More info about confguring the above DATABASES
dictionary can be found
here.
Step 3: Creating the mt_demo
app¶
The next step is to create the mt_demo
app which would be used for the rest of this tutorial
for verifying/demonstrating the behaviour of the library.
$ cd ${PROJECT_DIR}/mt_site
$ <activate the virtualenv for the project>
$ python manage.py startapp mt_demo
Note
All code snippets that follow assume that the venv
for the project is activated and the
working directory is set to ~/mt_site/
.
This would create a directory layout as follows:
mt_demo/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
Now add the following code to the models.py
file:
# assume that we're creating a hospital management system of sorts
from django.db import models
class Hospital(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
Once done, add the following code to the views.py
file.
import json
from django.http import HttpResponse
from django.views import View
from tenant_router.threadlocal import tls_tenant_manager
from tests.dummy_app.models import Hospital
class HospitalView(View):
def get(self, request):
data = list(Hospital.objects.all().values())
return HttpResponse(
content=json.dumps(data),
status=200
)
Add this view to the urls.py
file as follows:
# mt_site/urls.py
from django.urls import path, include
from mt_demo.views import HospitalView
urlpatterns = [
path('hospital/', HospitalView.as_view())
]
Once done, add this app to the INSTALLED_APPS
in settings.py
as follows:
# mt_site/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mt_site.apps.MtAppConfig'
]
Now, to perform migrations, run the following:
$ python manage.py makemigrations
$ python manage.py migrate
Load some test data as follows:
$ python manage.py shell
>>> from mt_site.models import Hospital
>>> h = Hospital.objects.create(name="Test hospital", address="1st street")
>>> quit()
Step 4: Running the server¶
Start the development server as follows:
$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
March 08, 2021 - 02:22:35
Django version 3.0, using settings 'tests.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Now make a http GET
call to http://127.0.0.1:8000/hospital/
as follows:
$ pip install requests
$ python manage.py shell
>>> import requests
>>> r = requests.get('http://127.0.0.1:8000/hospital/')
>>> print(r.json())
The expected response is as follows:
[{
"id": 1,
"name": "Test hospital",
"address": "1st street"
}]
With that we come to the end of this part. Now that we've built a basic single-tenant Django app from the ground-up, let's move on to the next part in order to make it multi-tenant.