Django-Tenant-Users: IntegrityError on permissions_usertenantpermissions_profile_id_key when creating a tenant
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:
django.db.utils.IntegrityError: ERROR: Duplicate key value breaks unique constraint 'permissions_usertenantpermissions_profile_id_key'
DETAIL: Key '(profile_id)=(8)' already exists.
I even cleared the table and tried but with all that the error is there
Here is the code for 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})
Here is the code of models.py in the shared app:
class SchoolUser(UserProfile):
ROLE_CHOICES = (
('director', 'Directeur'),
('accountant', 'Comptable'),
)
role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='accountant')
def is_director(self):
return self.role == 'director'
def is_accountant(self):
return self.role == 'accountant'
class School(TenantBase):
name = models.CharField(max_length=100) # Ajout du champ name
created_on = models.DateField(auto_now_add=True)
def __str__(self):
return self.name
class Domain(DomainMixin):
pass
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_save signals → 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.