Reputation: 11
Developing a Django project using django-tenants. In the moment of new user registration, the tenant has to be created on the host domain with address "project-url.ru/username/..."
Here is view.py with registration
def create_user_tenant(request):
user = UserClass.objects.get(username=request.POST['username'])
schema_name = f'{user.username}_schema'
try:
with transaction.atomic():
tenant = Tenant(schema_name=schema_name, user=user)
tenant.save()
logger.debug(f'Tenant {tenant} created')
domain = Domain(domain=HOST_NAME, tenant=tenant, is_primary=True)
domain.save()
logger.debug(f'Domain {domain} created for tenant {tenant}')
logger.info(f'Tenant for {user.username} was created.')
except IntegrityError as e:
logger.error(f'Error creating tenant or domain for user {user.username}: {e}')
except Exception as e:
logger.error(f'Unexpected error creating tenant or domain for user {user.username}: {e}')
def registration(request):
error_msg = ''
with transaction.atomic():
if request.POST:
logger.debug(f"Registration request")
form = UserRegistrationForm(data=request.POST)
if form.is_valid():
user = form.save()
logger.debug(f"User {user.username} has been registered")
create_user_tenant(request)
return redirect('login')
else:
error_msg = form.error_messages
logger.debug(f"Registration form is invalid. Error {error_msg}")
context = {
'form': UserRegistrationForm(),
'error_msg': error_msg,
}
return render(request, 'users/registration.html', context)
However, when saving the tenant tenant.save() I get an error:
The connection 'username_schema' doesn't exist.
At the same time, if I do the same via ./manage.py shell everything works correctly.
DB settings in settings.py:
DATABASES = {
"default": {
'ENGINE': "django_tenants.postgresql_backend",
.....
}
}
DATABASE_ROUTERS = (
'django_tenants.routers.TenantSyncRouter',
)
MIDDLEWARE = [
'django_tenants.middleware.main.TenantMainMiddleware',
...
]
Postgres runs in docker. Project run locally on the macos 14.5
Please help me figure out what the problem is with connecting to the database.
I would also be grateful if you could tell me how to organize the availability of a tenant by a domain of the format "project-url.ru/username/..." (but this is secondary)
Upvotes: 0
Views: 28