Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Changelog
* Add Django 5.2 and 6.0 support
* Add Python 3.13 and 3.14 support
* Fix an issue where the admin merge tag form redirect would fail when querystrings are present inside the URL
* Fix disabled TagField incorrectly stringifying and parsing non-string initial values (such as model instances or lists of tags)

6.1.0 (2024-09-29)
~~~~~~~~~~~~~~~~~~
Expand Down
10 changes: 10 additions & 0 deletions taggit/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ class TagField(forms.CharField):
widget = TagWidget

def clean(self, value):
if self.disabled:
if isinstance(value, str):
try:
return parse_tags(super().clean(value))
except ValueError:
raise forms.ValidationError(
_("Please provide a comma-separated list of tags.")
)
return [] if value is None else value

value = super().clean(value)
try:
return parse_tags(value)
Expand Down
19 changes: 14 additions & 5 deletions taggit/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
from django.utils.translation import gettext_lazy
from rest_framework import serializers

from taggit.utils import parse_tags


class TagList(list):
"""
Expand Down Expand Up @@ -79,12 +81,19 @@ def to_internal_value(self, value):
# In the future we should look at removing this feature so we can
# make this a simple ListField (if feasible)
if isinstance(value, str):
value = value.strip()
if not value:
value = "[]"
try:
value = json.loads(value)
except ValueError:
self.fail("invalid_json")
value = []
elif value.startswith("["):
try:
value = json.loads(value)
except ValueError:
self.fail("invalid_json")
else:
try:
value = json.loads(value)
except ValueError:
value = parse_tags(value)

if not isinstance(value, list):
self.fail("not_a_list", input_type=type(value).__name__)
Expand Down
49 changes: 49 additions & 0 deletions tests/test_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,52 @@ class TestForm(forms.Form):
form = TestForm()

self.assertFalse(form.has_changed())

def test_disabled_field_with_model_instances(self):
class TestForm(forms.Form):
tag = TagField(disabled=True)

initial_tags = [Tag(name="apple"), Tag(name="banana")]
form = TestForm(initial={"tag": initial_tags}, data={"tag": "other"})

self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data["tag"], initial_tags)

def test_disabled_field_with_string_initial(self):
class TestForm(forms.Form):
tag = TagField(disabled=True)

form = TestForm(initial={"tag": "apple,banana"}, data={"tag": "other"})

self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data["tag"], ["apple", "banana"])

def test_disabled_field_with_none_initial(self):
class TestForm(forms.Form):
tag = TagField(disabled=True, required=False)

form = TestForm(initial={"tag": None}, data={"tag": "other"})

self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data["tag"], [])

def test_disabled_field_in_model_form(self):
from .forms import FoodForm
from .models import Food

food = Food.objects.create(name="Apple")
food.tags.add("red", "sweet")

form = FoodForm(
data={"name": "Green Apple", "tags": "green,sour"},
instance=food,
)
form.fields["tags"].disabled = True

self.assertTrue(form.is_valid())
saved_food = form.save()
self.assertEqual(saved_food.name, "Green Apple")
self.assertSequenceEqual(
saved_food.tags.order_by("name").values_list("name", flat=True),
["red", "sweet"],
)
38 changes: 36 additions & 2 deletions tests/test_serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,28 @@ def test_taggit_serializer_field(self):

assert type(correct_value) is list

incorrect_value = "123"
# Non-list, non-string input raises ValidationError
incorrect_value = 123
with self.assertRaises(ValidationError):
serializer_field.to_internal_value(incorrect_value)

# Invalid JSON array raises ValidationError
with self.assertRaises(ValidationError):
incorrect_value = serializer_field.to_internal_value(incorrect_value)
serializer_field.to_internal_value("[invalid json")

# Comma-separated string parsing
parsed = serializer_field.to_internal_value("apple, banana, cherry")
self.assertEqual(sorted(parsed), ["apple", "banana", "cherry"])

# Quoted string parsing
parsed_quotes = serializer_field.to_internal_value(
'tag1, "multi word tag", tag2'
)
self.assertIn("multi word tag", parsed_quotes)

# Empty string parsing
empty_parsed = serializer_field.to_internal_value("")
self.assertEqual(empty_parsed, [])

representation = serializer_field.to_representation(correct_value)
self.assertIsInstance(representation, serializers.TagList)
Expand Down Expand Up @@ -69,6 +87,22 @@ def test_taggit_serializer_create_with_string(self):

assert {tag.name for tag in test_model.tags.all()} == {"1", "2", "3"}

def test_taggit_serializer_create_with_comma_separated_string(self):
"""
Test that comma-separated tag string is parsed and saved properly
"""
request_data = {"tags": "django, python, rest-framework"}

serializer = TestModelSerializer(data=request_data)
assert serializer.is_valid(), serializer.errors
test_model = serializer.save()

assert {tag.name for tag in test_model.tags.all()} == {
"django",
"python",
"rest-framework",
}

def test_taggit_removes_tags(self):
"""
Test if the old assigned tags are removed
Expand Down