Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bug in max_length calculation for CountryField with multiple=True #470

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
2 changes: 1 addition & 1 deletion django_countries/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
)
Expand Down
19 changes: 19 additions & 0 deletions django_countries/tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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="")
Expand Down