diff --git a/django_countries/fields.py b/django_countries/fields.py index 31564f4..5fa179f 100644 --- a/django_countries/fields.py +++ b/django_countries/fields.py @@ -298,7 +298,7 @@ def __init__(self, *args: Any, **kwargs: Any): # added to the available countries dictionary. if self.multiple: kwargs["max_length"] = ( - len(self.countries) + len(self.countries.countries) - 1 + sum(len(code) for code in self.countries.countries) ) diff --git a/django_countries/tests/test_fields.py b/django_countries/tests/test_fields.py index 49444c5..e4f0ff3 100644 --- a/django_countries/tests/test_fields.py +++ b/django_countries/tests/test_fields.py @@ -492,6 +492,25 @@ def test_contains(self): self.assertEqual(list(qs), [obj]) +class TestCountryFieldFirstRepeatMultiple(TestCase): + def setUp(self): + del countries.countries + + def tearDown(self): + del countries.countries + + @override_settings(COUNTRIES_FIRST=["NZ", "AU"], COUNTRIES_FIRST_REPEAT=True) + def test_max_length(self): + field = CountryField(multiple=True) + + # verify there are two additional choices + self.assertEqual(len(list(field.get_choices())), len(data.COUNTRIES) + 2) + + # but they should not change the field's max_length + expected_max_length = len(data.COUNTRIES) * 3 - 1 + self.assertEqual(field.max_length, expected_max_length) + + class TestCountryObject(TestCase): def test_hash(self): country = fields.Country(code="XX", flag_url="")