:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(organizations): regenerate slug when organization name changes (#96410)
Eleftheria Trivyzaki8257ed679042
diff --git a/ee/api/test/test_organization.py b/ee/api/test/test_organization.pyindex fdb105374599..e7febad04ae2 100644--- a/ee/api/test/test_organization.py+++ b/ee/api/test/test_organization.py@@ -56,7 +56,7 @@ class TestOrganizationEnterpriseAPI(APILicensedTest):self.assertLessEqual({"name": "#XXxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxX",- "slug": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-YYYY",+ "slug": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-yyyy",}.items(),response.json().items(),)diff --git a/posthog/api/test/test_organization.py b/posthog/api/test/test_organization.pyindex 2dcee300d8d1..95fb00f8b1f6 100644--- a/posthog/api/test/test_organization.py+++ b/posthog/api/test/test_organization.py@@ -152,9 +152,17 @@ class TestOrganizationAPI(APIBaseTest):response_rename = self.client.patch(f"/api/organizations/{self.organization.id}", {"name": "QWERTY"})self.assertEqual(response_rename.status_code, status.HTTP_200_OK)+ self.assertEqual(response_rename.json()["slug"], "qwerty")self.organization.refresh_from_db()self.assertEqual(self.organization.name, "QWERTY")+ self.assertEqual(self.organization.slug, "qwerty")++ response_slug = self.client.patch(f"/api/organizations/{self.organization.id}", {"slug": "hijacked"})++ self.assertEqual(response_slug.status_code, status.HTTP_200_OK)+ self.organization.refresh_from_db()+ self.assertEqual(self.organization.slug, "qwerty")def test_update_organization_if_owner(self):self.organization_membership.level = OrganizationMembership.Level.OWNERdiff --git a/posthog/models/organization.py b/posthog/models/organization.pyindex 51ef0f35104a..7e0677f0b501 100644--- a/posthog/models/organization.py+++ b/posthog/models/organization.py@@ -6,12 +6,13 @@ from typing import TYPE_CHECKING, Any, Literal, Optional, TypedDict, Unionfrom django.conf import settingsfrom django.contrib.postgres.fields import ArrayFieldfrom django.core.cache import cache-from django.db import models, transaction+from django.db import IntegrityError, models, transactionfrom django.db.models.query import QuerySetfrom django.db.models.query_utils import Qfrom django.db.models.signals import post_savefrom django.dispatch import receiverfrom django.utils import timezone+from django.utils.text import slugifyfrom django.utils.translation import gettext_lazy as _import structlog@@ -23,7 +24,7 @@ from posthog.constants import INVITE_DAYS_VALIDITY, MAX_SLUG_LENGTH, AvailableFefrom posthog.dataclasses import frozenfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.personal_api_key import PersonalAPIKey-from posthog.models.utils import LowercaseSlugField, UUIDTModel, create_with_slug, sane_repr+from posthog.models.utils import LowercaseSlugField, UUIDTModel, create_with_slug, generate_slug_candidates, sane_reprif TYPE_CHECKING:from posthog.models import Team, User@@ -210,6 +211,8 @@ class Organization(ModelActivityMixin, UUIDTModel):# General settingsname = models.CharField(max_length=64)+ # Name this instance last saw in the DB; save() compares it to self.name to detect a rename.+ _loaded_name: Optional[str] = Noneslug: LowercaseSlugField = LowercaseSlugField(unique=True, max_length=MAX_SLUG_LENGTH)logo_media = models.ForeignKey("posthog.UploadedMedia", on_delete=models.SET_NULL, null=True, blank=True)created_at = models.DateTimeField(auto_now_add=True)@@ -370,6 +373,47 @@ class Organization(ModelActivityMixin, UUIDTModel):__repr__ = sane_repr("name")+ @classmethod+ def from_db(cls, db: Any, field_names: Any, values: Any) -> "Organization":+ instance = super().from_db(db, field_names, values)+ instance._loaded_name = instance.__dict__.get("name")+ return instance++ def refresh_from_db(self, using: Any = None, fields: Any = None, from_queryset: Any = None) -> None:+ super().refresh_from_db(using=using, fields=fields, from_queryset=from_queryset)+ if fields is None or "name" in fields:+ self._loaded_name = self.name++ def save(self, *args: Any, **kwargs: Any) -> None:+ update_fields = kwargs.get("update_fields")+ name_is_written = update_fields is None or "name" in update_fields+ renamed = (+ not self._state.adding+ and name_is_written+ and self._loaded_name is not None+ and self._loaded_name != self.name+ )+ # Read self.name only after a rename is known, so a deferred name costs no query.+ base_slug = slugify(self.name)[:MAX_SLUG_LENGTH] if renamed else ""+ if renamed and base_slug != self.slug:+ if update_fields is not None:+ kwargs["update_fields"] = {*update_fields, "slug"}+ self._save_with_regenerated_slug(base_slug, *args, **kwargs)+ else:+ super().save(*args, **kwargs)+ if name_is_written and "name" in self.__dict__:+ self._loaded_name = self.name++ def _save_with_regenerated_slug(self, base_slug: str, *args: Any, **kwargs: Any) -> None:+ for candidate in generate_slug_candidates(base_slug):+ self.slug = candidate+ try:+ with transaction.atomic():+ return super().save(*args, **kwargs)+ except IntegrityError:+ continue+ raise Exception("Could not save organization with a unique slug in 10 tries!")+@propertydef _billing_plan_details(self) -> tuple[str | None, str | None]:"""diff --git a/posthog/models/test/test_organization_model.py b/posthog/models/test/test_organization_model.pyindex a277d0340a24..8e208cf09b2e 100644--- a/posthog/models/test/test_organization_model.py+++ b/posthog/models/test/test_organization_model.py@@ -38,6 +38,67 @@ class TestOrganization(BaseTest):opted_out = Organization.objects.create(name="Opted out org", uses_most_specific_access_resolution=False)self.assertFalse(opted_out.uses_most_specific_access_resolution)+ @parameterized.expand(+ [+ ("new_name", "Bar Baz Corp", "bar-baz-corp"),+ ("name_with_same_slug", "Foo Inc!", "foo-inc"),+ ]+ )+ def test_rename_updates_slug(self, _name, new_name, expected_slug):+ organization = Organization.objects.create(name="Foo Inc")+ organization.name = new_name+ organization.save()+ organization.refresh_from_db()+ self.assertEqual(organization.slug, expected_slug)++ def test_rename_to_taken_slug_appends_suffix(self):+ Organization.objects.create(name="Bar Baz")+ organization = Organization.objects.create(name="Foo Inc")+ organization.name = "Bar Baz"+ organization.save()+ in_memory_slug = organization.slug+ organization.refresh_from_db()+ self.assertRegex(organization.slug, r"^bar-baz-[a-z]{4}$")+ self.assertEqual(in_memory_slug, organization.slug)++ def test_save_without_rename_keeps_diverged_slug(self):+ Organization.objects.create(name="Foo Inc")+ organization = Organization.objects.create(name="Foo Inc")+ organization.refresh_from_db()+ suffixed_slug = organization.slug+ self.assertRegex(suffixed_slug, r"^foo-inc-[a-z]{4}$")+ organization.is_member_join_email_enabled = False+ organization.save()+ organization.refresh_from_db()+ self.assertEqual(organization.slug, suffixed_slug)++ def test_stale_instance_save_does_not_regenerate_slug(self):+ Organization.objects.create(name="Foo Inc")+ organization = Organization.objects.create(name="Foo Inc")+ organization.refresh_from_db()+ suffixed_slug = organization.slug+ stale_copy = Organization.objects.get(pk=organization.pk)+ organization.name = "Bar Baz"+ organization.save()+ stale_copy.is_member_join_email_enabled = False+ stale_copy.save()+ organization.refresh_from_db()+ self.assertEqual(organization.slug, suffixed_slug)++ @parameterized.expand(+ [+ ("name_included", ["name"], "new-name", "New Name"),+ ("name_excluded", ["is_member_join_email_enabled"], "foo-inc", "Foo Inc"),+ ]+ )+ def test_rename_with_update_fields(self, _name, update_fields, expected_slug, expected_name):+ organization = Organization.objects.create(name="Foo Inc")+ organization.name = "New Name"+ organization.save(update_fields=update_fields)+ organization.refresh_from_db()+ self.assertEqual(organization.slug, expected_slug)+ self.assertEqual(organization.name, expected_name)+def test_organization_active_invites(self):self.assertEqual(self.organization.invites.count(), 0)self.assertEqual(self.organization.active_invites.count(), 0)diff --git a/posthog/models/utils.py b/posthog/models/utils.pyindex 891e1f2dea7f..5816f4dd05c1 100644--- a/posthog/models/utils.py+++ b/posthog/models/utils.py@@ -256,15 +256,19 @@ def generate_random_short_suffix():return "".join(secrets.choice(string.ascii_letters) for _ in range(4))+def generate_slug_candidates(base_slug: str, attempts: int = 10) -> Iterator[str]:+ """Yield the plain slug first, then random-suffixed variants for disambiguation of duplicates."""+ yield base_slug+ for _ in range(attempts - 1):+ # Lowercase so the in-memory value matches what LowercaseSlugField stores.+ yield f"{base_slug[: MAX_SLUG_LENGTH - 5]}-{generate_random_short_suffix()}".lower()++def create_with_slug(create_func: Callable[..., T], default_slug: str = "", *args, **kwargs) -> T:"""Run model manager create function, making sure that the model is saved with a valid autogenerated slug field."""slugified_name = slugify(kwargs["name"])[:MAX_SLUG_LENGTH] if "name" in kwargs else default_slug- for retry_i in range(10):- # This retry loop handles possible duplicates by appending `-\d` to the slug in case of an IntegrityError- if not retry_i:- kwargs["slug"] = slugified_name- else:- kwargs["slug"] = f"{slugified_name[: MAX_SLUG_LENGTH - 5]}-{generate_random_short_suffix()}"+ for candidate in generate_slug_candidates(slugified_name):+ kwargs["slug"] = candidatetry:with transaction.atomic():return create_func(*args, **kwargs)