I’m using django-tenants, django-tenant-users, and django-organizations for multi-tenancy.
And I want users to automatically get redirected to their organization tenant.
Attempting to access https://127.0.0.1:3000/projects/ throws an error because the table doesn’t exist in the public schema. However, this should result in a redirect to https://127.0.0.1:3000/{subfolder_prefix}/{tenant_slug}/projects/ because the path('projects/', login_required(projects_view), name='projects')
is set within B.urls.py which is set as a TENANT_APP.
However I registered ‘appA’ as ‘SHARED_APP’ and ‘appB’ as a ‘TENANT_APP’ with the ‘ROOT_URLCONF’ is set to ‘appA.urls’ which has an path('', include('B.urls'))
. Is this inclusion short-circuiting the SHARED_APP and TENANT_APP division?
Currently, after login, users land on the root URL, and I redirected them to their organization-specific URL:
from django_tenants.utils import get_public_schema_name, get_subfolder_prefix
@login_required
def redirect_to_tenant_dashboard(request):
# Check if the user has any tenants other than the public one
user_tenants = request.user.tenants.exclude(schema_name=get_public_schema_name())
if user_tenants.exists():
# If the user has tenants other than public, redirect to the first tenant's dashboard
tenant_slug = user_tenants.first().slug
# Construct the tenant-specific dashboard URL
dashboard_url = f'/{get_subfolder_prefix()}/{tenant_slug}/'
print(f'dashboard_url: {dashboard_url}')
# Check if the constructed dashboard URL matches the current request URL
if dashboard_url == request.path:
# If the URLs match, no redirection is needed
return dashboard(request)
else:
# If the URLs don't match, redirect to the dashboard URL
return redirect(dashboard_url)
else:
# If the user only belongs to the public tenant, redirect to account settings
return redirect('account_settings')
Once the user is on the tenant url, the following middleware takes correctly over:
‘django_tenants.middleware.TenantSubfolderMiddleware’,
But this all feels more like a work around then an actual solution.
Does anyone know how to professionally handle redirecting users to their tenant-specific URL when accessing URLs from a TENANT_APP’s urls.py?