### Install django-tenants with pip Source: https://django-tenants.readthedocs.io/en/latest/install.html Use pip to install the django-tenants package. This is the first step in setting up multi-tenancy. ```bash pip install django-tenants ``` -------------------------------- ### Install Sphinx and Build Documentation Source: https://django-tenants.readthedocs.io/en/latest/install.html Install Sphinx using pip and use the make command within the docs directory to build HTML documentation. ```bash pip install Sphinx cd docs make html ``` -------------------------------- ### Run Example Projects with Docker Compose Source: https://django-tenants.readthedocs.io/en/latest/examples.html Commands to set up and run the django-tenants example projects using Docker Compose. This includes migrating the database and creating tenants. ```bash docker-compose run web bash ``` ```bash cd examples/tenant_tutorial ``` ```bash python manage.py migrate ``` ```bash python manage.py create_tenant ``` ```bash python manage.py runserver 0.0.0.0:8088 ``` -------------------------------- ### Run Tenant Tutorial Server Source: https://django-tenants.readthedocs.io/en/latest/examples.html Execute this command to start the development server for the tenant tutorial. Ensure your settings.py is configured. ```bash ./manage.py runserver ``` -------------------------------- ### TenantTestCase Example Source: https://django-tenants.readthedocs.io/en/latest/test.html Example of using TenantTestCase to automatically create a tenant and set the connection's schema for tests. TenantClient is used for making requests within the tenant's domain. ```python from django_tenants.test.cases import TenantTestCase from django_tenants.test.client import TenantClient class BaseSetup(TenantTestCase): def setUp(self): super().setUp() self.c = TenantClient(self.tenant) def test_user_profile_view(self): response = self.c.get(reverse('user_profile')) self.assertEqual(response.status_code, 200) ``` -------------------------------- ### Example Log Output with Tenant Context Source: https://django-tenants.readthedocs.io/en/latest/use.html Demonstrates the expected log output format when TenantContextFilter is enabled, showing schema and domain information prefixed to log messages. ```text [example:example.com] DEBUG 13:29 django.db.backends: (0.001) SELECT ... ``` -------------------------------- ### Migrate Shared Schemas Source: https://django-tenants.readthedocs.io/en/latest/install.html Run `migrate_schemas --shared` to create shared applications on the `public` schema. Ensure the database is empty for the initial setup. ```bash python manage.py migrate_schemas --shared ``` -------------------------------- ### Dump Data for Migration Source: https://django-tenants.readthedocs.io/en/latest/use.html Use the `dumpdata` management command to export all data from a single-tenant database into a JSON file, serving as a backup before migrating to a multi-tenant PostgreSQL setup. ```bash ./manage.py dumpdata --all --indent 2 > database.json ``` -------------------------------- ### Configure tenant usage in FastTenantTestCase Source: https://django-tenants.readthedocs.io/en/latest/test.html Override use_existing_tenant and use_new_tenant methods in FastTenantTestCase to customize behavior when an existing or new tenant is used during test setup. ```python class FastTenantTestCase(TenantTestCase): @classmethod def use_existing_tenant(cls): pass @classmethod def use_new_tenant(cls): pass ``` -------------------------------- ### Create Public Tenant Source: https://django-tenants.readthedocs.io/en/latest/use.html Run the `create_tenant` management command after migrating data to establish the 'public' tenant, making the application multi-tenant aware. ```bash ./manage.py create_tenant ``` -------------------------------- ### Configure Media File Storage with Tenant Subdirectory Source: https://django-tenants.readthedocs.io/en/latest/files.html Use MULTITENANT_RELATIVE_MEDIA_ROOT with %s formatting to place tenant media files in a subdirectory within MEDIA_ROOT. ```python # in settings.py MEDIA_ROOT = "absolute/path/to/your_project_dir/apps_dir/media/" MULTITENANT_RELATIVE_MEDIA_ROOT = "%s/other_dir" ``` -------------------------------- ### Create New Tenant Source: https://django-tenants.readthedocs.io/en/latest/use.html Use the create_tenant command to provision a new schema. Arguments like --domain-domain, --schema_name, and --name are required. Additional fields from TenantMixin can also be specified. ```bash ./manage.py create_tenant --domain-domain=newtenant.net --schema_name=new_tenant --name=new_tenant --description="New tenant" ``` -------------------------------- ### Create Public Tenant and Domain Source: https://django-tenants.readthedocs.io/en/latest/use.html Use this snippet to create the initial 'public' tenant and assign a primary domain. This is essential for making your main website available. ```python from customers.models import Client, Domain # create your public tenant tenant = Client(schema_name='public', name='Schemas Inc.', paid_until='2016-12-05', on_trial=False) tenant.save() # Add one or more domains for the tenant domain = Domain() domain.domain = 'my-domain.com' # don't add your port or www here! on a local server you'll want to use localhost here domain.tenant = tenant domain.is_primary = True domain.save() ``` -------------------------------- ### Create Tenant Superuser Source: https://django-tenants.readthedocs.io/en/latest/use.html Create a new superuser for a specific tenant schema using the create_tenant_superuser command with --username and --schema flags. ```bash ./manage.py create_tenant_superuser --username=admin --schema=customer1 ``` -------------------------------- ### Define Tenant-Specific Static Directories Source: https://django-tenants.readthedocs.io/en/latest/files.html Configure MULTITENANT_STATICFILES_DIRS to specify where TenantFileSystemFinder should look for tenant-specific static files. The %s placeholder is replaced with the tenant's schema_name. ```python # in settings.py MULTITENANT_STATICFILES_DIRS = [ os.path.join( "absolute/path/to/your_project_dir", "tenants/%s/static" ), ] ``` -------------------------------- ### Create a New Tenant and Domain Source: https://django-tenants.readthedocs.io/en/latest/use.html This snippet demonstrates creating a new tenant with a specific schema name and assigning it a primary domain. The `migrate_schemas` command is automatically called upon saving the tenant. ```python from customers.models import Client, Domain # create your first real tenant tenant = Client(schema_name='tenant1', name='Fonzy Tenant', paid_until='2014-12-05', on_trial=True) tenant.save() # migrate_schemas automatically called, your tenant is ready to be used! # Add one or more domains for the tenant domain = Domain() domain.domain = 'tenant.my-domain.com' # don't add your port or www here! domain.tenant = tenant domain.is_primary = True domain.save() ``` -------------------------------- ### Configure Static File Storage with Tenant Subdirectory Source: https://django-tenants.readthedocs.io/en/latest/files.html Use MULTITENANT_RELATIVE_STATIC_ROOT with %s formatting to place tenant static files in a subdirectory within STATIC_ROOT. ```python # in settings.py STATIC_ROOT = "absolute/path/to/your_project_dir/staticfiles" MULTITENANT_RELATIVE_STATIC_ROOT = "tenants/%s" ``` -------------------------------- ### Configure Static Files Finders Source: https://django-tenants.readthedocs.io/en/latest/files.html Insert TenantFileSystemFinder at the top of STATICFILES_FINDERS to prioritize tenant-specific files. This allows tenants to override static files. ```python # in settings.py STATICFILES_FINDERS = [ "django_tenants.staticfiles.finders.TenantFileSystemFinder", # Must be first "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", "compressor.finders.CompressorFinder", ] ``` ```python STATICFILES_FINDERS.insert(0, "django_tenants.staticfiles.finders.TenantFileSystemFinder") ``` -------------------------------- ### Configure Tenant-Aware Template Loaders Source: https://django-tenants.readthedocs.io/en/latest/files.html Insert TenantFileSystemLoader at the top of TEMPLATES 'loaders' and configure MULTITENANT_TEMPLATE_DIRS to enable tenant-specific template overrides. Use %s for schema_name formatting. ```python TEMPLATES = [ { ... "DIRS": ["absolute/path/to/your_project_dir/templates"], # -> Dirs used by the standard template loader "OPTIONS": { ... "loaders": [ "django_tenants.template.loaders.filesystem.Loader", # Must be first "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ], ... ... } ] MULTITENANT_TEMPLATE_DIRS = [ "absolute/path/to/your_project_dir/tenants/%s/templates" ] ``` -------------------------------- ### Configure Tenant Media File Storage Source: https://django-tenants.readthedocs.io/en/latest/files.html Set DEFAULT_FILE_STORAGE to TenantFileSystemStorage for per-tenant media directories. MULTITENANT_RELATIVE_MEDIA_ROOT can specify a subdirectory within MEDIA_ROOT. ```python # in settings.py DEFAULT_FILE_STORAGE = "django_tenants.files.storage.TenantFileSystemStorage" MULTITENANT_RELATIVE_MEDIA_ROOT = "" # (default: create sub-directory for each tenant) ``` -------------------------------- ### TenantTestCase with Additional Fields Source: https://django-tenants.readthedocs.io/en/latest/test.html Extends TenantTestCase to handle required fields on tenant and domain models by overriding setup_tenant and setup_domain methods. Includes TenantClient for request testing. ```python from django_tenants.test.cases import TenantTestCase from django_tenants.test.client import TenantClient class BaseSetup(TenantTestCase): @classmethod def setup_tenant(cls, tenant): """ Add any additional setting to the tenant before it get saved. This is required if you have required fields. """ tenant.required_value = "Value" return tenant def setup_domain(self, domain): """ Add any additional setting to the domain before it get saved. This is required if you have required fields. """ domain.ssl = True return domain def setUp(self): super().setUp() self.c = TenantClient(self.tenant) def test_user_profile_view(self): response = self.c.get(reverse('user_profile')) self.assertEqual(response.status_code, 200) ``` -------------------------------- ### Configure Database Engine Source: https://django-tenants.readthedocs.io/en/latest/install.html Update your Django settings to use the django_tenants PostgreSQL backend for multi-tenancy. ```python DATABASES = { 'default': { 'ENGINE': 'django_tenants.postgresql_backend', # .. } } ``` -------------------------------- ### Dynamic INSTALLED_APPS for Multi-type Tenants Source: https://django-tenants.readthedocs.io/en/latest/use.html Dynamically set `INSTALLED_APPS` by iterating through the `TENANT_TYPES` configuration to include apps from all defined tenant types. ```python INSTALLED_APPS = [] for schema in TENANT_TYPES: INSTALLED_APPS += [app for app in TENANT_TYPES[schema]["APPS"] if app not in INSTALLED_APPS] ``` -------------------------------- ### Define Tenant and Domain Models Source: https://django-tenants.readthedocs.io/en/latest/install.html Create your tenant model inheriting from TenantMixin and your domain model inheriting from DomainMixin. The schema_name field is required for TenantMixin. ```python from django.db import models from django_tenants.models import TenantMixin, DomainMixin class Client(TenantMixin): name = models.CharField(max_length=100) paid_until = models.DateField() on_trial = models.BooleanField() created_on = models.DateField(auto_now_add=True) # default true, schema will be automatically created and synced when it is saved auto_create_schema = True class Domain(DomainMixin): pass ``` -------------------------------- ### Define SHARED_APPS and TENANT_APPS Source: https://django-tenants.readthedocs.io/en/latest/install.html Configure `SHARED_APPS` for globally synced applications and `TENANT_APPS` for tenant-specific applications. `INSTALLED_APPS` is constructed from these. ```python SHARED_APPS = ( 'django_tenants', 'customers', 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', ) TENANT_APPS = ( 'myapp.hotels', 'myapp.houses', ) INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] ``` -------------------------------- ### Configure Tenant Middleware Source: https://django-tenants.readthedocs.io/en/latest/install.html Add TenantMainMiddleware to the top of your MIDDLEWARE setting to manage tenant requests. ```python MIDDLEWARE = ( 'django_tenants.middleware.main.TenantMainMiddleware', #... ) ``` -------------------------------- ### Run Command on All Schemas Source: https://django-tenants.readthedocs.io/en/latest/use.html Use the all_tenants_command wrapper to execute any management command across all available tenant schemas. ```bash ./manage.py all_tenants_command loaddata ``` -------------------------------- ### Apply Specific Migrations with Fake Source: https://django-tenants.readthedocs.io/en/latest/use.html Apply specific migration files (e.g., for 'myapp' version 0001_initial) and mark them as fake using the --fake option, useful when switching to South migrations. ```bash ./manage.py migrate_schemas myapp 0001_initial --fake ``` -------------------------------- ### Enable Tenant-Aware Caching Source: https://django-tenants.readthedocs.io/en/latest/install.html Configure Django's CACHES setting to use django_tenants' make_key and reverse_key functions for tenant-aware caching. ```python CACHES = { "default": { ... 'KEY_FUNCTION': 'django_tenants.cache.make_key', 'REVERSE_KEY_FUNCTION': 'django_tenants.cache.reverse_key', }, } ``` -------------------------------- ### Configure Sub-folder Support Source: https://django-tenants.readthedocs.io/en/latest/install.html Set `TENANT_SUBFOLDER_PREFIX` to enable sub-folder routing for tenants. This requires a specific middleware and a non-blank prefix. ```python TENANT_SUBFOLDER_PREFIX = "clients" ``` -------------------------------- ### Separate WSGI for Main Website Source: https://django-tenants.readthedocs.io/en/latest/install.html Create a separate WSGI file to manage settings and URL configurations for the main website, distinct from tenant applications. ```python # wsgi_main_website.py import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings_public") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() ``` -------------------------------- ### Create Custom Tenant Command Source: https://django-tenants.readthedocs.io/en/latest/use.html Inherit from BaseTenantCommand to create custom management commands that can run on all tenants. Ensure all necessary imports are included. ```python from django_tenants.management.commands import BaseTenantCommand # rest of your imports class Command(BaseTenantCommand): COMMAND_NAME = 'awesome command' # rest of your command ``` -------------------------------- ### Run Default Schema Migrations Source: https://django-tenants.readthedocs.io/en/latest/use.html Execute migrate_schemas without any schema arguments to migrate only SHARED_APPS for the public schema or TENANT_APPS for tenant schemas, respecting Django settings. ```bash ./manage.py migrate_schemas ``` -------------------------------- ### Run Tenant Migrations in Parallel Source: https://django-tenants.readthedocs.io/en/latest/use.html Execute tenant migrations concurrently using the --executor=multiprocessing argument. This can speed up the migration process by utilizing multiple processes. ```bash python manage.py migrate_schemas --executor=multiprocessing ``` -------------------------------- ### Configure Extra Set Tenant Method Source: https://django-tenants.readthedocs.io/en/latest/use.html Specify EXTRA_SET_TENANT_METHOD_PATH in settings.py to point to a custom method that executes additional logic when switching tenants, useful for scenarios like read replicas. ```python EXTRA_SET_TENANT_METHOD_PATH = 'tenant_multi_types_tutorial.set_tenant_utils.extra_set_tenant_stuff' ``` -------------------------------- ### Configure Tenant-Aware Static Files Storage Source: https://django-tenants.readthedocs.io/en/latest/files.html Set STATICFILES_STORAGE to TenantStaticFilesStorage for tenant-aware collection of static files. MULTITENANT_RELATIVE_STATIC_ROOT controls the subdirectory within STATIC_ROOT for tenant files. ```python # in settings.py STATICFILES_STORAGE = "django_tenants.staticfiles.storage.TenantStaticFilesStorage" MULTITENANT_RELATIVE_STATIC_ROOT = "" # (default: create sub-directory for each tenant) ``` -------------------------------- ### Database Router for Tenant Sync Source: https://django-tenants.readthedocs.io/en/latest/install.html Configure `DATABASE_ROUTERS` to include the `TENANT_SYNC_ROUTER` for managing tenant schema synchronization. ```python DATABASE_ROUTERS = [ # .. TENANT_SYNC_ROUTER # .. ] ``` -------------------------------- ### Configure Tenant Context Filter for Logging Source: https://django-tenants.readthedocs.io/en/latest/use.html Integrate TenantContextFilter into settings.LOGGING to enrich log entries with the current schema_name and domain_url. This requires defining filters, formatters, and handlers. ```python # settings.py LOGGING = { 'filters': { 'tenant_context': { '()': 'django_tenants.log.TenantContextFilter' }, }, 'formatters': { 'tenant_context': { 'format': '[%(schema_name)s:%(domain_url)s] ' \ '%(levelname)-7s %(asctime)s %(message)s', }, }, 'handlers': { 'console': { 'filters': ['tenant_context'], }, }, } ``` -------------------------------- ### List Migrations Source: https://django-tenants.readthedocs.io/en/latest/use.html Use the --list option with migrate_schemas to view pending migrations for schemas. ```bash ./manage.py migrate_schemas --list ``` -------------------------------- ### Specify Tenant and Domain Models Source: https://django-tenants.readthedocs.io/en/latest/install.html Set `TENANT_MODEL` and `TENANT_DOMAIN_MODEL` to point to your custom tenant and domain models, respectively. This is crucial for tenant identification. ```python TENANT_MODEL = "customers.Client" # app.Model TENANT_DOMAIN_MODEL = "customers.Domain" # app.Model ``` -------------------------------- ### Multi-type Tenant Configuration Source: https://django-tenants.readthedocs.io/en/latest/use.html Configure Django-tenants for multiple tenant types by setting `HAS_MULTI_TYPE_TENANTS` and `MULTI_TYPE_DATABASE_FIELD`. Define `TENANT_TYPES` with specific `APPS` and `URLCONF` for each type. ```python HAS_MULTI_TYPE_TENANTS = True MULTI_TYPE_DATABASE_FIELD = 'type' # or whatever the name you call the database field TENANT_TYPES = { "public": { # this is the name of the public schema from get_public_schema_name "APPS": ['django_tenants', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # shared apps here ], "URLCONF": "tenant_multi_types_tutorial.urls_public", # url for the public type here }, "type1": { "APPS": ['django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.sessions', 'django.contrib.messages', # type1 apps here ], "URLCONF": "tenant_multi_types_tutorial.urls_type1", }, "type2": { "APPS": ['django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.sessions', 'django.contrib.messages', # type1 apps here ], "URLCONF": "tenant_multi_types_tutorial.urls_type2", } } ``` -------------------------------- ### Create Missing Schemas Source: https://django-tenants.readthedocs.io/en/latest/use.html The create_missing_schemas command compares the tenant table with existing schemas and creates any schemas that are missing. ```bash ./manage.py create_missing_schemas ``` -------------------------------- ### Run Tests with Docker Compose Source: https://django-tenants.readthedocs.io/en/latest/test.html Execute django-tenants tests using docker-compose for a containerized environment. ```bash docker-compose run django-tenants-test ``` -------------------------------- ### Run Command on Individual Schema Source: https://django-tenants.readthedocs.io/en/latest/use.html Utilize the tenant_command wrapper to execute any management command on a single, specified schema. If no schema is provided, you will be prompted to enter one. ```bash ./manage.py tenant_command loaddata ``` -------------------------------- ### Define Extra Set Tenant Method Source: https://django-tenants.readthedocs.io/en/latest/use.html Implement the custom method specified in EXTRA_SET_TENANT_METHOD_PATH. This method accepts the database wrapper class and the tenant object as arguments. ```python def extra_set_tenant_stuff(wrapper_class, tenant): pass ``` -------------------------------- ### Run Command on Individual Schema with Specified Schema Source: https://django-tenants.readthedocs.io/en/latest/use.html Execute a management command on a specific schema using tenant_command with the --schema argument. ```bash ./manage.py tenant_command loaddata --schema=customer1 ``` -------------------------------- ### Configure PostGIS Backend Source: https://django-tenants.readthedocs.io/en/latest/use.html To enable PostGIS support, add the ORIGINAL_BACKEND setting to your Django settings file, pointing to the PostGIS backend. ```python ORIGINAL_BACKEND = "django.contrib.gis.db.backends.postgis" ``` -------------------------------- ### Configure Database Routers Source: https://django-tenants.readthedocs.io/en/latest/install.html Add TenantSyncRouter to your DATABASE_ROUTERS setting to ensure correct app syncing for shared and tenant schemas. ```python DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) ``` -------------------------------- ### Tenant Schema Synchronization Signals Source: https://django-tenants.readthedocs.io/en/latest/use.html Use these signals to hook into tenant schema creation, migration needs, and completion events. Ensure `auto_create_schema` is False for `schema_needs_to_be_sync` to trigger. Useful for background tenant creation with tools like Celery. ```python @receiver(schema_needs_to_be_sync, sender=TenantMixin) def created_user_client_in_background(sender, **kwargs): client = kwargs['tenant'] print ("created_user_client_in_background %s" % client.schema_name) from clients.tasks import setup_tenant task = setup_tenant.delay(client) ``` ```python @receiver(post_schema_sync, sender=TenantMixin) def created_user_client(sender, **kwargs): client = kwargs['tenant'] # send email to client to as tenant is ready to use ``` ```python @receiver(schema_migrated, sender=run_migrations) def handle_schema_migrated(sender, **kwargs): schema_name = kwargs['schema_name'] # recreate materialized views in the schema ``` ```python @receiver(schema_migrate_message, sender=run_migrations) def handle_schema_migrate_message(**kwargs): message = kwargs['message'] # recreate materialized views in the schema ``` -------------------------------- ### Run Tests with Custom Migration Executor Source: https://django-tenants.readthedocs.io/en/latest/test.html Run django-tenants tests using a custom migration executor, such as multiprocessing. ```bash EXECUTOR=multiprocessing ./manage.py test django_tenants.tests ``` -------------------------------- ### Clone Tenant Source: https://django-tenants.readthedocs.io/en/latest/use.html Clone an existing tenant schema using the clone_tenant command. For detailed options, refer to the command's help message. ```bash ./manage.py clone_tenant ``` -------------------------------- ### Run Default Tests Source: https://django-tenants.readthedocs.io/en/latest/test.html Execute the default test suite for django-tenants from the project's dts_test_project directory. ```bash ./manage.py test django_tenants.tests ``` -------------------------------- ### Enable Tenant Limit Set Calls Source: https://django-tenants.readthedocs.io/en/latest/use.html Set TENANT_LIMIT_SET_CALLS to True in settings.py to minimize search_path calls per request, improving performance in high-volume environments. The default is False. ```python #in settings.py: TENANT_LIMIT_SET_CALLS = True ``` -------------------------------- ### Run Code Across All Tenants Source: https://django-tenants.readthedocs.io/en/latest/use.html Iterate through all tenants using `get_tenant_model().objects.all()` and execute custom code within each tenant's context using `tenant_context`. ```python from django_tenants.utils import tenant_context, get_tenant_model for tenant in get_tenant_model().objects.all(): with tenant_context(tenant): pass # do whatever you want in that tenant ``` -------------------------------- ### Custom Test Domain and Schema Names Source: https://django-tenants.readthedocs.io/en/latest/test.html Demonstrates how to customize the test domain name and schema name by overriding get_test_tenant_domain and get_test_schema_name static methods within a TenantTestCase. ```python from django_tenants.test.cases import TenantTestCase from django_tenants.test.client import TenantClient class BaseSetup(TenantTestCase): @staticmethod def get_test_tenant_domain(): return 'tenant.my_domain.com' @staticmethod def get_test_schema_name(): return 'tester' ``` -------------------------------- ### Import FastTenantTestCase Source: https://django-tenants.readthedocs.io/en/latest/test.html Import the FastTenantTestCase class from django_tenants.test.cases to use it in your tests. ```python from django_tenants.test.cases import FastTenantTestCase ``` -------------------------------- ### Migrate Specific Schema Source: https://django-tenants.readthedocs.io/en/latest/use.html Use the migrate_schemas command with the --schema argument to apply migrations to a particular tenant's schema. ```bash ./manage.py migrate_schemas --schema=customer1 ``` -------------------------------- ### Configure Template Context Processors Source: https://django-tenants.readthedocs.io/en/latest/install.html Ensure 'django.template.context_processors.request' is in TEMPLATES 'OPTIONS' 'context_processors' to access the tenant on request objects. ```python TEMPLATES = [ { #... 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', #... ], }, }, ] ``` -------------------------------- ### Flush Tables Before Loading Data Source: https://django-tenants.readthedocs.io/en/latest/use.html Execute `sqlflush` followed by `dbshell` to ensure newly created tables in the PostgreSQL database are empty before loading migrated data. ```bash ./manage.py sqlflush | ./manage.py dbshell ``` -------------------------------- ### Tenant Subfolder Middleware Source: https://django-tenants.readthedocs.io/en/latest/install.html Include `TenantSubfolderMiddleware` in your `MIDDLEWARE` setting when using sub-folder support for tenant routing. ```python MIDDLEWARE = ( 'django_tenants.middleware.TenantSubfolderMiddleware', #... ) ``` -------------------------------- ### Rename Schema with Arguments Source: https://django-tenants.readthedocs.io/en/latest/use.html Provide the old and new schema names directly as arguments to the rename_schema command using --rename_from and --rename_to. ```bash ./manage.py rename_schema --rename_from old_name --rename_to new_name ``` -------------------------------- ### Collect Static Files for Tenants Source: https://django-tenants.readthedocs.io/en/latest/files.html Use the collectstatic_schemas management command to collect static files for all tenants. The --schema argument can filter for a specific tenant. ```bash ./manage.py collectstatic_schemas --schema=your_tenant_schema_name ``` -------------------------------- ### Load Migrated Data Source: https://django-tenants.readthedocs.io/en/latest/use.html Use the `loaddata` management command to import the previously exported JSON data into the new multi-tenant PostgreSQL database. ```bash ./manage.py loaddata --format json database.json ``` -------------------------------- ### Use tenant_context as a Context Manager Source: https://django-tenants.readthedocs.io/en/latest/use.html This context manager executes database queries using the schema associated with a given tenant model object. Import `tenant_context` from `django_tenants.utils`. ```python from django_tenants.utils import tenant_context with tenant_context(tenant): # All commands here are ran under the schema from the `tenant` object # Restores the `SEARCH_PATH` to its original value ``` -------------------------------- ### Configure Apache for Subdomain Routing Source: https://django-tenants.readthedocs.io/en/latest/install.html Set up Apache's VirtualHost to route all subdomains and the main domain to your Django project's WSGI script. ```apache ServerName mywebsite.com ServerAlias *.mywebsite.com mywebsite.com WSGIScriptAlias / "/path/to/django/scripts/mywebsite.wsgi" ``` -------------------------------- ### Tenant Model with Type Field Source: https://django-tenants.readthedocs.io/en/latest/use.html Add a 'type' field to your tenant model to support multi-type tenants. Use `get_tenant_type_choices()` for the field's choices. ```python from django_tenants.utils import get_tenant_type_choices class Client(TenantMixin): type = models.CharField(max_length=100, choices=get_tenant_type_choices()) ``` -------------------------------- ### Configure Public Schema URLConf Source: https://django-tenants.readthedocs.io/en/latest/install.html Use PUBLIC_SCHEMA_URLCONF to route requests for the public schema to a specific URL configuration, distinct from the tenant's ROOT_URLCONF. ```python PUBLIC_SCHEMA_URLCONF = 'myproject.urls_public' ``` -------------------------------- ### Register Tenant Model with Admin Source: https://django-tenants.readthedocs.io/en/latest/install.html Use TenantAdminMixin to register your tenant model with the Django admin. This mixin helps manage tenant-specific admin actions. ```python from django.contrib import admin from django_tenants.admin import TenantAdminMixin from myapp.models import Client @admin.register(Client) class ClientAdmin(TenantAdminMixin, admin.ModelAdmin): list_display = ('name', 'paid_until') ``` -------------------------------- ### Use tenant_context as a Decorator Source: https://django-tenants.readthedocs.io/en/latest/use.html Decorate a function with `tenant_context` to automatically switch to the schema of the provided tenant object for all database operations within that function. ```python from django_tenants.utils import tenant_context @tenant_context(tenant) def my_func(): # All commands in this function are ran under the schema from the `tenant` object ``` -------------------------------- ### Include Debug Toolbar URLs Source: https://django-tenants.readthedocs.io/en/latest/use.html Manually add django-debug-toolbar URLs to your `urls.py` in both public and tenant configurations when `settings.DEBUG` is True. This requires importing `debug_toolbar` and `include`. ```python from django.conf import settings from django.conf.urls import include if settings.DEBUG: import debug_toolbar urlpatterns += patterns( '', url(r'^__debug__/', include(debug_toolbar.urls)), ) ``` -------------------------------- ### Use schema_context as a Context Manager Source: https://django-tenants.readthedocs.io/en/latest/use.html This utility allows you to execute database queries within a specific schema. Ensure you import `schema_context` from `django_tenants.utils`. ```python from django_tenants.utils import schema_context with schema_context(schema_name): # All commands here are ran under the schema `schema_name` # Restores the `SEARCH_PATH` to its original value ``` -------------------------------- ### Rename Schema Source: https://django-tenants.readthedocs.io/en/latest/use.html Rename an existing schema and update its associated Client entry using the rename_schema command. You will be prompted for the old and new names if not provided as arguments. ```bash ./manage.py rename_schema ``` -------------------------------- ### Add Extra Search Paths Source: https://django-tenants.readthedocs.io/en/latest/install.html Use `PG_EXTRA_SEARCH_PATHS` to specify additional schemas that should be visible to all queries, such as schemas for PostgreSQL extensions. ```python PG_EXTRA_SEARCH_PATHS = ['extensions'] ``` -------------------------------- ### Configure flush_data in FastTenantTestCase Source: https://django-tenants.readthedocs.io/en/latest/test.html Override the flush_data class method in FastTenantTestCase to control whether tables are emptied after each test run. The default is True, which means data is cleared. ```python class FastTenantTestCase(TenantTestCase): @classmethod def flush_data(cls): return True ``` -------------------------------- ### Use schema_context as a Decorator Source: https://django-tenants.readthedocs.io/en/latest/use.html Apply `schema_context` as a decorator to a function to ensure all database operations within that function are executed against the specified schema. ```python from django_tenants.utils import schema_context @schema_context(schema_name) def my_func(): # All commands in this function are ran under the schema `schema_name` ``` -------------------------------- ### Delete Tenant Source: https://django-tenants.readthedocs.io/en/latest/use.html The delete_tenant command removes a tenant and its associated PostgreSQL schema. This action is irreversible and will proceed even if auto_drop_schema is set to False. ```bash ./manage.py delete_tenant ``` -------------------------------- ### Disable Tenant App Coloring in Admin Source: https://django-tenants.readthedocs.io/en/latest/use.html Set `TENANT_COLOR_ADMIN_APPS` to `False` in your settings to disable the default dark green coloring for tenant apps in the Django admin interface. ```python TENANT_COLOR_ADMIN_APPS = False ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.