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.00
# Django Countries
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: django-countries
7
- **Language**: Python
8
- **Installation**: `pip install django-countries`
9
- **Django Version Support**: 3.2 - 5.0
10
- **Optional Dependencies**: `pip install django-countries[pyuca]` for improved country name sorting
11
12
## Core Imports
13
14
```python
15
import django_countries
16
from django_countries import countries
17
from django_countries.fields import CountryField, Country
18
```
19
20
## Basic Usage
21
22
```python
23
# In models.py
24
from django.db import models
25
from django_countries.fields import CountryField
26
27
class Person(models.Model):
28
name = models.CharField(max_length=100)
29
country = CountryField()
30
31
# Usage with country objects
32
person = Person.objects.create(name="John", country="US")
33
print(person.country.name) # "United States"
34
print(person.country.code) # "US"
35
print(person.country.flag) # "/static/flags/us.gif"
36
37
# Working with the global countries instance
38
from django_countries import countries
39
40
# Iterate through all countries
41
for country in countries:
42
print(f"{country.code}: {country.name}")
43
44
# Get country by code
45
us_name = countries.name("US") # "United States"
46
us_alpha3 = countries.alpha3("US") # "USA"
47
48
# Find country by name
49
us_code = countries.by_name("United States") # "US"
50
```
51
52
## Architecture
53
54
Django Countries follows Django conventions and provides multiple integration layers:
55
56
- **Core Countries**: Global countries registry with ISO 3166-1 data, configuration options, and lookup methods
57
- **Model Integration**: CountryField for Django models with automatic Country object descriptors
58
- **Form Integration**: Specialized form fields and widgets with lazy-loaded choices
59
- **Admin Integration**: Optimized admin filters for country selection
60
- **Framework Extensions**: Support for Django REST Framework, GraphQL, and template tags
61
- **Internationalization**: Full translation support with fallback handling for country names
62
63
## Capabilities
64
65
### Model Fields
66
67
Django model field for storing country codes with rich Country object functionality, supporting single and multiple country selection, custom country lists, and automatic validation.
68
69
```python { .api }
70
class CountryField(models.CharField):
71
def __init__(
72
self,
73
countries=None,
74
countries_flag_url=None,
75
countries_str_attr="code",
76
blank_label=None,
77
multiple=None,
78
multiple_unique=True,
79
multiple_sort=True,
80
**kwargs
81
): ...
82
```
83
84
[Model Fields](./model-fields.md)
85
86
### Countries Registry
87
88
Core countries registry providing ISO 3166-1 country data with lookup, translation, and configuration capabilities for customizing country lists and display options.
89
90
```python { .api }
91
class Countries:
92
def alpha2(self, code) -> str: ...
93
def alpha3(self, code) -> str: ...
94
def numeric(self, code, padded=False): ...
95
def name(self, code) -> str: ...
96
def by_name(self, country, *, regex=False, language="en", insensitive=True): ...
97
def __iter__(self): ...
98
```
99
100
[Countries Registry](./countries-registry.md)
101
102
### Form Fields and Widgets
103
104
Specialized Django form fields and widgets for country selection with lazy-loaded choices, flag display support, and JavaScript integration for enhanced user interfaces.
105
106
```python { .api }
107
class LazyTypedChoiceField(forms.TypedChoiceField): ...
108
class LazyTypedMultipleChoiceField(forms.TypedMultipleChoiceField): ...
109
class CountrySelectWidget(widgets.Select): ...
110
```
111
112
[Form Fields and Widgets](./form-fields-widgets.md)
113
114
### Django REST Framework Integration
115
116
Serializer fields and mixins for Django REST Framework providing country serialization with flexible output formats including code-only, name-only, and dictionary representations.
117
118
```python { .api }
119
class CountryField(serializers.ChoiceField):
120
def __init__(self, *, country_dict=None, name_only=None, countries=None, **kwargs): ...
121
122
class CountryFieldMixin:
123
def build_standard_field(self, field_name, model_field): ...
124
```
125
126
[Django REST Framework](./django-rest-framework.md)
127
128
### Template Tags
129
130
Django template tags for accessing country data in templates, providing simple interfaces for retrieving individual countries and complete country lists.
131
132
```python { .api }
133
@register.simple_tag
134
def get_country(code): ...
135
136
@register.simple_tag
137
def get_countries(): ...
138
```
139
140
[Template Tags](./template-tags.md)
141
142
### GraphQL Support
143
144
GraphQL type definitions for country data integration with graphene-django, providing structured country information for GraphQL APIs.
145
146
```python { .api }
147
class Country(graphene.ObjectType):
148
name = graphene.String()
149
code = graphene.String()
150
alpha3 = graphene.String()
151
numeric = graphene.Int()
152
ioc_code = graphene.String()
153
```
154
155
[GraphQL Support](./graphql-support.md)
156
157
### Admin Integration
158
159
Django admin integration with optimized country filters and form field handling for efficient country-based filtering and selection in the Django admin interface.
160
161
```python { .api }
162
class CountryFilter(admin.FieldListFilter): ...
163
```
164
165
[Admin Integration](./admin-integration.md)
166
167
## Configuration
168
169
Global settings with `COUNTRIES_` prefix for customizing country behavior:
170
171
```python { .api }
172
# settings.py
173
COUNTRIES_FLAG_URL = "flags/{code}.gif"
174
COUNTRIES_COMMON_NAMES = True
175
COUNTRIES_OVERRIDE = {"US": "America"}
176
COUNTRIES_ONLY = ["US", "CA", "MX"]
177
COUNTRIES_FIRST = ["US"]
178
COUNTRIES_FIRST_REPEAT = False
179
COUNTRIES_FIRST_BREAK = "-------"
180
COUNTRIES_FIRST_SORT = False
181
```
182
183
## Types
184
185
```python { .api }
186
from typing import Union, Optional, List, Dict, NamedTuple, TypedDict
187
from django_stubs_ext import StrPromise
188
189
CountryCode = Union[str, int, None]
190
CountryName = Union[StrPromise, ComplexCountryName]
191
192
class CountryTuple(NamedTuple):
193
code: str
194
name: str
195
196
class AltCodes(NamedTuple):
197
alpha3: str
198
numeric: Optional[int]
199
200
class ComplexCountryName(TypedDict):
201
name: StrPromise
202
names: List[StrPromise]
203
alpha3: str
204
numeric: int
205
ioc_code: str
206
207
class Country:
208
code: str
209
name: str
210
flag: str
211
alpha3: str
212
numeric: Optional[int]
213
numeric_padded: Optional[str]
214
ioc_code: str
215
flag_css: str
216
unicode_flag: str
217
```