diff --git a/backend/product/models.py b/backend/product/models.py index b31c113..4617358 100644 --- a/backend/product/models.py +++ b/backend/product/models.py @@ -99,8 +99,22 @@ class SubCategoryModel(models.Model): return self.name def save(self, *args, **kwargs): + # Ensure slug is present and unique. If a slug (auto or custom) would + # collide with an existing product, append a numeric suffix. if not self.slug: - self.slug = slugify(self.name, allow_unicode=True) + base_slug = slugify(self.name, allow_unicode=True) + else: + # Normalize a provided slug + base_slug = slugify(self.slug, allow_unicode=True) + + slug_candidate = base_slug + counter = 1 + # Exclude self.pk to allow updating the same instance + while ProductModel.objects.filter(slug=slug_candidate).exclude(pk=self.pk).exists(): + slug_candidate = f"{base_slug}-{counter}" + counter += 1 + + self.slug = slug_candidate super().save(*args, **kwargs)