[Django]-Django multitenant: how to customize django setting "ACCOUNT_EMAIL_VERIFICATION" per tenant?

4👍

You can compute the settings at runtime, since it’s simply a python code.

Set that specific code programmatically, using your preferred way. One example:

# predefine the settings per tenant
ACCOUNT_EMAIL_VERIFICATION_PER_TENANT = {
    "tenant_x": "mandatory",
    "tenant_y": "optional",
}

# implement get_tenant 

def get_tenant():
    # here be tenant logic
    pass

this_tenant = get_tenant()
ACCOUNT_EMAIL_VERIFICATION = ACCOUNT_EMAIL_VERIFICATION_PER_TENANT[get_tenant()]

Or you can have multiple settings files and join them as you wish. Here’s how django does.

Oh and if you want to separate the logic from the settings file and have it run before evaluating the settings perhaps, you can inspect what is the trail of execution when you launch your server (e.g. starting from manage.py and insert your get_tenant logic somewhere in between). Most probably it will be somewhere starting from the wsgi.py file – where the application instance gets created and all the django fun begins.

When it comes to programming, you are always in control.

👤Adelin

3👍

I stumbled upon this situation, and my dynamic solution is a middleware as follows without any hardcoding tenant’s names

from django.conf import settings
from django.db import connection
from django_tenants.utils import get_public_schema_name, get_tenant_model

class TenantSettingsMiddleWare:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        self.request = request
        self.overload_settings()
        response = self.get_response(request)
        return response

    def overload_settings(self):
        current_schema_obj = get_tenant_model().objects.get(schema_name=connection.schema_name)
        settings.DEFAULT_FROM_EMAIL = 'admin@{}'.format(current_schema_obj.domains.last())


Cheers 🍻🍻🍻

0👍

Solved in following way:

In settings.py:

try:
    ACCOUNT_EMAIL_VERIFICATION = os.environ['ACCOUNT_EMAIL_VERIFICATION_OVERRIDE']
except KeyError:
    ACCOUNT_EMAIL_VERIFICATION = 'mandatory'

In wsgi.py file of the tenant where e-mail verification is optional:

os.environ['ACCOUNT_EMAIL_VERIFICATION_OVERRIDE'] = 'optional'

wsgi files for the other tenants remain unchanged.


Gave the bounty to Adelin as he suggested to look into the wsgi file.

👤Davy

Leave a comment