diff --git a/apps/main/methods.py b/apps/main/methods.py index 845a99a4..d5f307eb 100644 --- a/apps/main/methods.py +++ b/apps/main/methods.py @@ -1,11 +1,13 @@ """Main app methods.""" import logging -from typing import Tuple, Optional from django.conf import settings from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception from geoip2.models import City +from typing import Union, Tuple, Optional +import pycountry + from main import models logger = logging.getLogger(__name__) @@ -83,3 +85,16 @@ def determine_user_city(ip_addr: str) -> Optional[City]: except Exception as ex: logger.warning(f'GEOIP Base exception: {ex}') return None + + +def determine_subdivision( + country_alpha2_code: str, + subdivision_code: Union[str, int] +) -> pycountry.Subdivision: + """ + :param country_alpha2_code: country code according to ISO 3166-1 alpha-2 standard + :param subdivision_code: subdivision code according to ISO 3166-2 without country code prefix + :return: subdivision + """ + iso3166_2_subdivision_code = f'{country_alpha2_code}-{subdivision_code}' + return pycountry.subdivisions.get(code=iso3166_2_subdivision_code) diff --git a/requirements/base.txt b/requirements/base.txt index 7ae1fe1f..e492e114 100644 --- a/requirements/base.txt +++ b/requirements/base.txt @@ -17,6 +17,7 @@ markdown django-filter==2.1.0 djangorestframework-xml geoip2==2.9.0 +pycountry==19.8.18 django-phonenumber-field[phonenumbers]==2.1.0 django-timezone-field==3.1