Here follows an example in how to use django-tenants-url
.
This is a very basic example how to see the UUID of a tenant and use it in the headers. For more robust and secure approach we also provide views, serializers, utils and some permissions and handlers that can be used accordingly.
pip install django-tenants-url
After installing django-tenants-url
, add it into the settings.
INSTALLED_APPS = [
...
'django_tenants',
'django_tenants_url',
...
]
Let's create a tenant custom app and add it into the settings.
-
Create the app
django-admin startapp tenant
-
Add the app to the
INSTALLED_APPS
. -
INSTALLED_APPS = [ ... 'django_tenants', 'django_tenants_url', 'tenant', ... ]
More settings will be needed but we will back later on to update the settings.
-
Inside the newly created
tenant
in themodels.py
.from django_tenants_url.models import TenantMixin, DomainMixin, TenantUserMixin class Client(TenantMixin): pass class Domain(DomainMixin): pass class TenantUser(TenantUserMixin): pass
-
Create migrations.
python manage.py makemigrations
-
Run migrations.
python manage.py migrate_schemas
With the models created we can now update the settings.py
.
-
Add extra needed settings.
INSTALLED_APPS = [...] TENANT_MODEL = 'tenant.Client' # needed from django-tenants TENANT_DOMAIN_MODEL = 'tenant.Domain' # needed from django-tenants # DTU_TENANT_USER_MODEL DTU_TENANT_USER_MODEL = 'tenant.TenantUser' # unique to django-tenants-url
-
Update the
MIDDLEWARE
.MIDDLEWARE = [ 'django_tenants_url.middleware.RequestUUIDTenantMiddleware', 'django.middleware.security.SecurityMiddleware', ... ]
Once the first request hits the server, it should create the public tenant and public domain.
django-tenants-url
provides out-of-the-box views to help you with all of the process as well
as some functions that can be used to get some of the information like the UUID needed
to be used in the header of a request and map to user schema.
from django_tenants_url.utils import get_tenants
tenants = get_tenants()
print(tenants)
[
{
"id": 1,
"tenant_name": "Public",
"tenant_uuid": "a66b19e4-3985-42a1-87e1-338707c4a203"
}
]
Using the uuid a66b19e4-3985-42a1-87e1-338707c4a203
we can now use the header
that maps the user with the schema.
curl --header "X_REQUEST_ID: a66b19e4-3985-42a1-87e1-338707c4a203" -v http://localhost:8000/my-view