A Django application that provides country choices for use with forms, flag icons static files, and a country field for models.
npx @tessl/cli install tessl/pypi-django-countries@7.6.0A comprehensive Django application that provides ISO 3166-1 compliant country functionality for web applications. It offers a specialized CountryField for Django models that stores country data with full country object details including names, codes, and flags. The package includes country choices for forms based on international standards, static flag icon files for visual representation, and supports translated country names for internationalization.
pip install django-countriespip install django-countries[pyuca] for improved country name sortingimport django_countries
from django_countries import countries
from django_countries.fields import CountryField, Country# In models.py
from django.db import models
from django_countries.fields import CountryField
class Person(models.Model):
name = models.CharField(max_length=100)
country = CountryField()
# Usage with country objects
person = Person.objects.create(name="John", country="US")
print(person.country.name) # "United States"
print(person.country.code) # "US"
print(person.country.flag) # "/static/flags/us.gif"
# Working with the global countries instance
from django_countries import countries
# Iterate through all countries
for country in countries:
print(f"{country.code}: {country.name}")
# Get country by code
us_name = countries.name("US") # "United States"
us_alpha3 = countries.alpha3("US") # "USA"
# Find country by name
us_code = countries.by_name("United States") # "US"Django Countries follows Django conventions and provides multiple integration layers:
Django model field for storing country codes with rich Country object functionality, supporting single and multiple country selection, custom country lists, and automatic validation.
class CountryField(models.CharField):
def __init__(
self,
countries=None,
countries_flag_url=None,
countries_str_attr="code",
blank_label=None,
multiple=None,
multiple_unique=True,
multiple_sort=True,
**kwargs
): ...Core countries registry providing ISO 3166-1 country data with lookup, translation, and configuration capabilities for customizing country lists and display options.
class Countries:
def alpha2(self, code) -> str: ...
def alpha3(self, code) -> str: ...
def numeric(self, code, padded=False): ...
def name(self, code) -> str: ...
def by_name(self, country, *, regex=False, language="en", insensitive=True): ...
def __iter__(self): ...Specialized Django form fields and widgets for country selection with lazy-loaded choices, flag display support, and JavaScript integration for enhanced user interfaces.
class LazyTypedChoiceField(forms.TypedChoiceField): ...
class LazyTypedMultipleChoiceField(forms.TypedMultipleChoiceField): ...
class CountrySelectWidget(widgets.Select): ...Serializer fields and mixins for Django REST Framework providing country serialization with flexible output formats including code-only, name-only, and dictionary representations.
class CountryField(serializers.ChoiceField):
def __init__(self, *, country_dict=None, name_only=None, countries=None, **kwargs): ...
class CountryFieldMixin:
def build_standard_field(self, field_name, model_field): ...Django template tags for accessing country data in templates, providing simple interfaces for retrieving individual countries and complete country lists.
@register.simple_tag
def get_country(code): ...
@register.simple_tag
def get_countries(): ...GraphQL type definitions for country data integration with graphene-django, providing structured country information for GraphQL APIs.
class Country(graphene.ObjectType):
name = graphene.String()
code = graphene.String()
alpha3 = graphene.String()
numeric = graphene.Int()
ioc_code = graphene.String()Django admin integration with optimized country filters and form field handling for efficient country-based filtering and selection in the Django admin interface.
class CountryFilter(admin.FieldListFilter): ...Global settings with COUNTRIES_ prefix for customizing country behavior:
# settings.py
COUNTRIES_FLAG_URL = "flags/{code}.gif"
COUNTRIES_COMMON_NAMES = True
COUNTRIES_OVERRIDE = {"US": "America"}
COUNTRIES_ONLY = ["US", "CA", "MX"]
COUNTRIES_FIRST = ["US"]
COUNTRIES_FIRST_REPEAT = False
COUNTRIES_FIRST_BREAK = "-------"
COUNTRIES_FIRST_SORT = Falsefrom typing import Union, Optional, List, Dict, NamedTuple, TypedDict
from django_stubs_ext import StrPromise
CountryCode = Union[str, int, None]
CountryName = Union[StrPromise, ComplexCountryName]
class CountryTuple(NamedTuple):
code: str
name: str
class AltCodes(NamedTuple):
alpha3: str
numeric: Optional[int]
class ComplexCountryName(TypedDict):
name: StrPromise
names: List[StrPromise]
alpha3: str
numeric: int
ioc_code: str
class Country:
code: str
name: str
flag: str
alpha3: str
numeric: Optional[int]
numeric_padded: Optional[str]
ioc_code: str
flag_css: str
unicode_flag: str