or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

admin-integration.mdcountries-registry.mddjango-rest-framework.mdform-fields-widgets.mdgraphql-support.mdindex.mdmodel-fields.mdtemplate-tags.md
tile.json

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.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/django-countries@7.6.x

To install, run

npx @tessl/cli install tessl/pypi-django-countries@7.6.0

index.mddocs/

Django Countries

A 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.

Package Information

  • Package Name: django-countries
  • Language: Python
  • Installation: pip install django-countries
  • Django Version Support: 3.2 - 5.0
  • Optional Dependencies: pip install django-countries[pyuca] for improved country name sorting

Core Imports

import django_countries
from django_countries import countries
from django_countries.fields import CountryField, Country

Basic Usage

# 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"

Architecture

Django Countries follows Django conventions and provides multiple integration layers:

  • Core Countries: Global countries registry with ISO 3166-1 data, configuration options, and lookup methods
  • Model Integration: CountryField for Django models with automatic Country object descriptors
  • Form Integration: Specialized form fields and widgets with lazy-loaded choices
  • Admin Integration: Optimized admin filters for country selection
  • Framework Extensions: Support for Django REST Framework, GraphQL, and template tags
  • Internationalization: Full translation support with fallback handling for country names

Capabilities

Model Fields

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
    ): ...

Model Fields

Countries Registry

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): ...

Countries Registry

Form Fields and Widgets

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): ...

Form Fields and Widgets

Django REST Framework Integration

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 REST Framework

Template Tags

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(): ...

Template Tags

GraphQL Support

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()

GraphQL Support

Admin Integration

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): ...

Admin Integration

Configuration

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 = False

Types

from 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