Installation and settings
-
Install the django-tenants library and add it to your dependencies.
-
Update the database engine to use the Django-Tenants Postgres backend.
-
A custom database router can then be added to
settings.py. -
Add the
TenantMainMiddlewareto theMIDDLEWARElist. It should be added afterCommonMiddlewareto avoid any errors.
App and model
In this example, you’ll create two Django apps. The first,app, will contain the models used to manage tenants and domains, along with any views that are publicly accessible. The second app, dashboard, will be tenant-specific and will contain functionality and views intended only for individual tenants.
app/models.py. The Client model is used to create all tenants. The Domain model is used to associate subdomains with the tenants you create.
Other settings
Because some apps should be available globally across the project, while others should be isolated per tenant, you’ll need to adjust howINSTALLED_APPS is defined.
Start by defining a SHARED_APPS list, which replaces the traditional INSTALLED_APPS and includes apps that are shared across all tenants. Next, create a TENANT_APPS list containing only the apps that should be available to individual tenants. Finally, define INSTALLED_APPS as a combination of both lists.
The SHARED_APPS list should also include the django_tenants app and the main app application that manages tenants and domains.
settings.py, configure Django-Tenants, so that it knows where your core tenant and domain models are defined.
settings.py, replace the original ROOT_URLCONF with a new configuration pointing to urls_tenants, which you’ll create shortly. Then, define PUBLIC_SCHEMA_URLCONF to point to your original urls.py file, which will continue to handle all public (non-tenant) views.
Views
Below are two simple example views that illustrate the difference between public views and tenant-specific views.Public View
This view lives in the sharedapp application and is accessible across the entire project, regardless of tenant.
Tenant-Specific View
This view belongs to thedashboard application and is only available within a tenant context. It uses request.tenant to access tenant-specific data.
Tenant URL Configuration
Next, create aurls_tenants.py file to define routes that should only be accessible to tenants. This file references views from the tenant-only dashboard app.
Public URL Configuration
Finally, keep your public routes in the existingurls.py file. These URLs are served from the public schema and remain accessible without a tenant context.
Deploying to Sevalla
Before deploying your application, create migrations to create the new models in the database.migrate_schemas command from Django-Tenants.