fix(attribute): restore backward compatibility for invalid slugs

Replace ValidationError with a warning when creating Attributes with invalid slugs. This change allows existing code to continue functioning while alerting users to potential issues.
This commit is contained in:
Mike 2024-09-01 21:24:18 -07:00
parent 3e7563338f
commit 8f18d5e7e2
2 changed files with 14 additions and 9 deletions

View file

@ -2,6 +2,7 @@
from __future__ import annotations
import warnings
from typing import TYPE_CHECKING, Optional
from django.contrib.contenttypes.models import ContentType
@ -311,13 +312,10 @@ class Attribute(models.Model):
super().clean_fields(exclude=exclude)
if not self.slug.isidentifier():
raise ValidationError(
{
"slug": _(
"Slug must be a valid Python identifier (no spaces, "
+ "special characters, or leading digits).",
),
},
warnings.warn(
f"Slug '{self.slug}' is not a valid Python identifier. "
+ "Consider updating it.",
stacklevel=3,
)
def get_choices(self):

View file

@ -167,8 +167,15 @@ class TestAttributeModel(django.TestCase):
@pytest.mark.django_db
def test_attribute_create_with_invalid_slug():
with pytest.raises(ValidationError):
def test_attribute_create_with_invalid_slug() -> None:
"""
Test that creating an Attribute with an invalid slug raises a UserWarning.
This test ensures that when an Attribute is created with a slug that is not
a valid Python identifier, a UserWarning is raised. The warning should
indicate that the slug is invalid and suggest updating it.
"""
with pytest.warns(UserWarning):
Attribute.objects.create(
name="Test Attribute",
slug="123-invalid",