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

New features added #9

Merged
merged 2 commits into from
Jan 31, 2024
Merged
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
28 changes: 26 additions & 2 deletions django_country_kit/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class Country:
- _code (str): The country code.
"""

def __init__(self, code=None, custom_countries=None):
def __init__(self, code=None, name=None, custom_countries=None):
"""
Initialize a Country instance.

Expand All @@ -41,7 +41,11 @@ def __init__(self, code=None, custom_countries=None):
self._countries_data = custom_countries
else:
self._countries_data = get_countries()
self._code = code

if name:
self._code = self.get_code_from_name(name)
elif code:
self._code = code

@property
def countries_data(self):
Expand All @@ -53,7 +57,27 @@ def name(self) -> str:
"""Get the name of the country."""
return self._countries_data.get(self._code, {}).get('name', '')

@property
def code(self) -> str:
"""Get the code of the country."""
return self._code

@property
def alpha3(self) -> str:
"""Get the alpha3 code of the country."""
return self._countries_data.get(self._code, {}).get('alpha3', '')

def get_code_from_name(self, name: str) -> str:
"""
Get the country code from the country name.

Args:
name (str): The name of the country.

Returns:
str: The country code.
"""
for code, data in self._countries_data.items():
if data['name'] == name:
return code
return ''
6 changes: 5 additions & 1 deletion django_country_kit/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
For more information, see Django documentation on internationalization:
https://docs.djangoproject.com/en/5.0/topics/i18n/
"""
import sys

from django.conf import settings
from django.utils.translation import gettext_lazy as _
Expand Down Expand Up @@ -294,6 +295,9 @@ def get_countries():

include_countries = getattr(settings, "INCLUDE_COUNTRIES", [])
if include_countries:
countries = countries | include_countries
if sys.version_info >= (3, 9):
countries = countries | include_countries
else:
countries = {**countries, **include_countries}

return dict(sorted(countries.items(), key=lambda x: x[1]['name']))
4 changes: 4 additions & 0 deletions django_country_kit/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,13 @@ def formfield(self, **kwargs):
return forms.TypedChoiceField(**defaults)

def get_prep_value(self, value):
if not self.multiple:
return super().get_prep_value(value)
return '' if value is None else ",".join(map(str, value))

def get_db_prep_value(self, value, connection, prepared=False):
if not self.multiple:
return super().get_db_prep_value(value, connection, prepared)
if not prepared and not isinstance(value, str):
value = self.get_prep_value(value)
return value
Expand Down
25 changes: 24 additions & 1 deletion django_country_kit/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
This module defines test classes for the 'CountryField' and 'CountryWidget'
components in your Django app. It includes tests for the 'CountryField' model field
and the 'CountryWidget' form widget, including the behavior when using the
'OVERRIDE_COUNTRIES' and 'EXCLUDE_COUNTRIES' settings.
'OVERRIDE_COUNTRIES', 'EXCLUDE_COUNTRIES', 'INCLUDE_COUNTRIES' settings.

Usage:
- Include this module in your Django app's 'tests' package.
Expand All @@ -28,6 +28,7 @@
from django.core import exceptions
from django.test import TestCase, override_settings

from .base import Country
from .data import DATA
from .fields import CountryField, MultiSelectList

Expand All @@ -43,8 +44,10 @@ class CountryFieldTests(TestCase):
- test_country_field_choices(): Test that choices are populated from COUNTRIES.
- test_country_field_override_countries(): Test behavior when using OVERRIDE_COUNTRIES setting.
- test_country_field_exclude_countries(): Test behavior when using EXCLUDE_COUNTRIES setting.
- test_country_field_include_countries(): Test behavior when using INCLUDE_COUNTRIES setting.
- test_country_field_get_choices_method(): Test the overridden get_choices method.
- test_country_field_validate_method(): Test the overridden validate method for multiple selection.
- test_country_by_name(): Test retrieving a country by name.
"""

def test_country_field_max_length(self):
Expand Down Expand Up @@ -83,6 +86,17 @@ def test_country_field_exclude_countries(self):
self.assertEqual(len(field.choices), len(DATA) - len(settings.EXCLUDE_COUNTRIES))
logger.info("test_country_field_exclude_countries ✓")

@override_settings(INCLUDE_COUNTRIES={"UT": {"name": "Utopia", "alpha3": "UTP"}})
def test_country_field_include_countries(self):
"""
Test behavior when using INCLUDE_COUNTRIES setting.
"""
field = CountryField()
included_country_codes = settings.INCLUDE_COUNTRIES.keys()
all_country_codes = [country[0] for country in field.choices]
self.assertTrue(all(country in all_country_codes for country in included_country_codes))
logger.info("test_country_field_include_countries ✓")

def test_country_field_get_choices_method(self):
"""
Test the overridden get_choices method.
Expand All @@ -109,6 +123,15 @@ def test_country_field_validate_method(self):
field.validate(invalid_value, None)
logger.info("test_country_field_validate_method ✓")

def test_country_by_name(self):
"""
Test retrieving a country by name.
"""
country_name = "United States"
country = Country(name=country_name)
self.assertEqual(country.code, "US")
logger.info("test_country_by_name ✓")


class MultiSelectListTests(TestCase):
"""
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

setup(
name='django-country-kit',
version="0.0.2",
version="0.0.3",
author='Pescheck IT',
author_email='[email protected]',
description='Countries for django',
Expand Down
Loading