CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-django-countries

A Django application that provides country choices for use with forms, flag icons static files, and a country field for models.

Pending
Overview
Eval results
Files

countries-registry.mddocs/

Countries Registry

Core countries registry providing ISO 3166-1 country data with lookup, translation, and configuration capabilities. The Countries class manages the complete list of countries with support for custom country lists, translated names, and flexible display options.

Capabilities

Countries Class

Main container for ISO 3166-1 countries with configuration options and lookup methods. Provides iteration, indexing, and comprehensive country code conversion functionality.

class Countries:
    def __init__(self):
        """Initialize countries registry with default configuration."""

    @property
    def countries(self) -> Dict[str, CountryName]:
        """Dictionary of country codes to country names/objects."""

    def alpha2(self, code: CountryCode) -> str:
        """
        Convert any country code format to ISO 3166-1 alpha-2 code.
        
        Parameters:
        - code: Union[str, int, None] - Country code in any format
        
        Returns:
        - str: Two-letter country code, empty string if not found
        """

    def alpha3(self, code: CountryCode) -> str:
        """
        Convert country code to ISO 3166-1 alpha-3 format.
        
        Parameters:
        - code: Union[str, int, None] - Country code in any format
        
        Returns:
        - str: Three-letter country code, empty string if not found
        """

    def numeric(self, code: CountryCode, padded: bool = False) -> Union[int, str, None]:
        """
        Convert country code to ISO 3166-1 numeric format.
        
        Parameters:
        - code: Union[str, int, None] - Country code in any format
        - padded: bool - Return zero-padded string instead of integer
        
        Returns:
        - Union[int, str, None]: Numeric code or None if not found
        """

    def ioc_code(self, code: CountryCode) -> str:
        """  
        Get International Olympic Committee code for country.
        
        Parameters:
        - code: Union[str, int, None] - Country code in any format
        
        Returns:
        - str: IOC three-letter code, empty string if not found
        """

    def name(self, code: CountryCode) -> str:
        """
        Get country name for given code.
        
        Parameters:
        - code: Union[str, int, None] - Country code in any format
        
        Returns:
        - str: Country name in current language, empty string if not found
        """

    def by_name(
        self, 
        country: str, 
        *, 
        regex: bool = False,
        language: str = "en", 
        insensitive: bool = True
    ) -> Union[str, Set[str]]:
        """
        Find country code(s) by country name.
        
        Parameters:
        - country: str - Country name to search for
        - regex: bool - Use regular expression matching
        - language: str - Language for name matching
        - insensitive: bool - Case-insensitive matching
        
        Returns:
        - Union[str, Set[str]]: Country code or set of codes if regex=True
        """

    def __iter__(self):
        """Iterate through countries sorted by translated name."""

    def __len__(self) -> int:
        """Number of countries including configuration adjustments."""

    def __contains__(self, code) -> bool:
        """Check if country code exists in registry."""

    def __getitem__(self, index):
        """Access countries by index or slice."""

Global Countries Instance

Pre-configured global countries instance for general use.

from django_countries import countries

# Global instance ready to use
countries: Countries

Usage Examples

Basic Country Lookups

from django_countries import countries

# Get country name
print(countries.name("US"))        # "United States"
print(countries.name("GB"))        # "United Kingdom"

# Convert between code formats  
print(countries.alpha3("US"))      # "USA"
print(countries.alpha2("USA"))     # "US"
print(countries.numeric("US"))     # 840
print(countries.numeric("US", padded=True))  # "840"

# IOC codes
print(countries.ioc_code("US"))    # "USA"

# Find by name
print(countries.by_name("United States"))     # "US"
print(countries.by_name("united states"))     # "US" (case insensitive)
print(countries.by_name("America", regex=True))  # {"US"} (set result)

Iteration and Access

# Iterate through all countries (sorted by name)
for country in countries:
    print(f"{country.code}: {country.name}")

# Access by index
first_country = countries[0]
print(f"{first_country.code}: {first_country.name}")

# Slice access
first_ten = countries[:10]

# Check membership
if "US" in countries:
    print("US is a valid country code")

# Get count
print(f"Total countries: {len(countries)}")

Advanced Name Searches

# Regex searches (return sets)
island_countries = countries.by_name(r".*Island.*", regex=True)
print(island_countries)  # {"CK", "NF", "SB", "TC", "VI", ...}

# Case-sensitive exact match
code = countries.by_name("Macedonia", insensitive=False)

# Search in different language
with translation.override('de'):
    code = countries.by_name("Deutschland", language='de')

Configuration

Custom Countries Lists

Create specialized Countries instances with custom configurations:

from django_countries import Countries

# Custom instance with specific countries only
eu_countries = Countries()
eu_countries.only = ["DE", "FR", "IT", "ES", "NL", "BE"]

# Custom instance with overrides
custom_countries = Countries()  
custom_countries.override = {"US": "America", "GB": "Britain"}
custom_countries.common_names = True

Countries Configuration Options

Configure via Django settings or Countries instance attributes:

# Via Django settings
COUNTRIES_OVERRIDE = {
    "US": "America",
    "GB": "Britain", 
    "AU": None  # Exclude Australia
}

COUNTRIES_ONLY = ["US", "CA", "MX"]  # Include only these countries

COUNTRIES_FIRST = ["US", "CA"]       # Show these first
COUNTRIES_FIRST_REPEAT = True        # Repeat in main list
COUNTRIES_FIRST_BREAK = "-------"    # Separator after first countries
COUNTRIES_FIRST_SORT = True          # Sort first countries

COUNTRIES_COMMON_NAMES = True        # Use common names like "South Korea"

Accessing Configuration

from django_countries import countries

# Access configuration
print(countries.get_option("first"))          # ["US", "CA"] 
print(countries.get_option("common_names"))   # True
print(countries.get_option("override"))       # {"US": "America", ...}

Translation Support

Language-Specific Names

from django.utils.translation import override

# Get names in different languages
with override('es'):
    print(countries.name("US"))  # "Estados Unidos"

with override('fr'):  
    print(countries.name("US"))  # "États-Unis"

# Find by translated name
with override('de'):
    code = countries.by_name("Deutschland")  # "DE"

Translation Context Management

from django_countries import no_translation_fallback

# Disable translation fallback
with no_translation_fallback():
    # Only show translations, no fallback to English
    country_name = countries.name("DE")

Country Data Access

Alternative Codes Access

# Access alternative code mappings
alt_codes = countries.alt_codes["US"]
print(alt_codes.alpha3)   # "USA" 
print(alt_codes.numeric)  # 840

# IOC code mappings
ioc_codes = countries.ioc_codes["US"]  # "USA"

Historical Names

# Access shadowed/historical names
shadowed = countries.shadowed_names.get("CZ", [])
# May include historical names like "Czech Republic"

Types

from typing import Union, Optional, Dict, Set, List, NamedTuple
from django_stubs_ext import StrPromise

CountryCode = Union[str, int, None]
CountryName = Union[StrPromise, ComplexCountryName]

class CountryTuple(NamedTuple):
    code: str
    name: str
    
    def __repr__(self) -> str:
        """Display as standard tuple for template compatibility."""

class AltCodes(NamedTuple):
    alpha3: str
    numeric: Optional[int]

class ComplexCountryName(TypedDict):
    name: StrPromise
    names: List[StrPromise]
    alpha3: str
    numeric: int
    ioc_code: str

Install with Tessl CLI

npx tessl i tessl/pypi-django-countries

docs

admin-integration.md

countries-registry.md

django-rest-framework.md

form-fields-widgets.md

graphql-support.md

index.md

model-fields.md

template-tags.md

tile.json