Hello,
I’m using Django with django-tenants and django-tenant-users to manage multi-tenant accounts.
I’m having an issue when creating a new tenant:
When I try to create a new user + its tenant through my view, I get the following error:
IntegrityError at /school_login
ERROR: duplicate key value violates unique constraint "permissions_usertenantpermissions_profile_id_key"
DETAIL: Key (profile_id)=(6) already exists.
However, the table is empty before running the creation (no records in permissions_usertenantpermissions).
My school_login view:
def school_login(request):
if request.method == 'POST':
form = CreateSchoolForm(request.POST)
if form.is_valid():
sigle = form.cleaned_data['sigle']
slug = form.cleaned_data['sigle'].lower()
email = form.cleaned_data['email']
password = form.cleaned_data['password']
# Create the user
user = SchoolUser.objects.create_user(
email=email,
password=password,
)
user.role = 'director'
user.is_verified = True
user.save()
# Create the tenant
tenant, domain = provision_tenant(
tenant_name=sigle,
tenant_slug=slug,
owner=user,
is_superuser=True,
is_staff=True,
)
# Authenticate and login
authenticated_user = authenticate(request, username=email, password=password)
if authenticated_user:
login(request, authenticated_user)
tenant_domain = get_tenant_domain_model().objects.get(tenant=tenant).domain
return HttpResponseRedirect(f"http://{tenant_domain}/")
else:
form = CreateSchoolForm()
return render(request, 'school_login.html', {'form': form})
What I’ve tried
-
Clearing all data in the database → same error.
-
Checking if I’m calling
tenant.add_user()twice → only called once. -
Checking for
post_savesignals → nothing special in my project. -
Configuring the settings.py
Why does provision_tenant try to create the same user profile twice in permissions_usertenantpermissions, even though I only call it once?
How can I fix this IntegrityError and properly create a tenant with its owner?
Thanks in advance