or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

countries-registry.mddocs/

0

# Countries Registry

1

2

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.

3

4

## Capabilities

5

6

### Countries Class

7

8

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

9

10

```python { .api }

11

class Countries:

12

def __init__(self):

13

"""Initialize countries registry with default configuration."""

14

15

@property

16

def countries(self) -> Dict[str, CountryName]:

17

"""Dictionary of country codes to country names/objects."""

18

19

def alpha2(self, code: CountryCode) -> str:

20

"""

21

Convert any country code format to ISO 3166-1 alpha-2 code.

22

23

Parameters:

24

- code: Union[str, int, None] - Country code in any format

25

26

Returns:

27

- str: Two-letter country code, empty string if not found

28

"""

29

30

def alpha3(self, code: CountryCode) -> str:

31

"""

32

Convert country code to ISO 3166-1 alpha-3 format.

33

34

Parameters:

35

- code: Union[str, int, None] - Country code in any format

36

37

Returns:

38

- str: Three-letter country code, empty string if not found

39

"""

40

41

def numeric(self, code: CountryCode, padded: bool = False) -> Union[int, str, None]:

42

"""

43

Convert country code to ISO 3166-1 numeric format.

44

45

Parameters:

46

- code: Union[str, int, None] - Country code in any format

47

- padded: bool - Return zero-padded string instead of integer

48

49

Returns:

50

- Union[int, str, None]: Numeric code or None if not found

51

"""

52

53

def ioc_code(self, code: CountryCode) -> str:

54

"""

55

Get International Olympic Committee code for country.

56

57

Parameters:

58

- code: Union[str, int, None] - Country code in any format

59

60

Returns:

61

- str: IOC three-letter code, empty string if not found

62

"""

63

64

def name(self, code: CountryCode) -> str:

65

"""

66

Get country name for given code.

67

68

Parameters:

69

- code: Union[str, int, None] - Country code in any format

70

71

Returns:

72

- str: Country name in current language, empty string if not found

73

"""

74

75

def by_name(

76

self,

77

country: str,

78

*,

79

regex: bool = False,

80

language: str = "en",

81

insensitive: bool = True

82

) -> Union[str, Set[str]]:

83

"""

84

Find country code(s) by country name.

85

86

Parameters:

87

- country: str - Country name to search for

88

- regex: bool - Use regular expression matching

89

- language: str - Language for name matching

90

- insensitive: bool - Case-insensitive matching

91

92

Returns:

93

- Union[str, Set[str]]: Country code or set of codes if regex=True

94

"""

95

96

def __iter__(self):

97

"""Iterate through countries sorted by translated name."""

98

99

def __len__(self) -> int:

100

"""Number of countries including configuration adjustments."""

101

102

def __contains__(self, code) -> bool:

103

"""Check if country code exists in registry."""

104

105

def __getitem__(self, index):

106

"""Access countries by index or slice."""

107

```

108

109

### Global Countries Instance

110

111

Pre-configured global countries instance for general use.

112

113

```python { .api }

114

from django_countries import countries

115

116

# Global instance ready to use

117

countries: Countries

118

```

119

120

## Usage Examples

121

122

### Basic Country Lookups

123

124

```python

125

from django_countries import countries

126

127

# Get country name

128

print(countries.name("US")) # "United States"

129

print(countries.name("GB")) # "United Kingdom"

130

131

# Convert between code formats

132

print(countries.alpha3("US")) # "USA"

133

print(countries.alpha2("USA")) # "US"

134

print(countries.numeric("US")) # 840

135

print(countries.numeric("US", padded=True)) # "840"

136

137

# IOC codes

138

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

139

140

# Find by name

141

print(countries.by_name("United States")) # "US"

142

print(countries.by_name("united states")) # "US" (case insensitive)

143

print(countries.by_name("America", regex=True)) # {"US"} (set result)

144

```

145

146

### Iteration and Access

147

148

```python

149

# Iterate through all countries (sorted by name)

150

for country in countries:

151

print(f"{country.code}: {country.name}")

152

153

# Access by index

154

first_country = countries[0]

155

print(f"{first_country.code}: {first_country.name}")

156

157

# Slice access

158

first_ten = countries[:10]

159

160

# Check membership

161

if "US" in countries:

162

print("US is a valid country code")

163

164

# Get count

165

print(f"Total countries: {len(countries)}")

166

```

167

168

### Advanced Name Searches

169

170

```python

171

# Regex searches (return sets)

172

island_countries = countries.by_name(r".*Island.*", regex=True)

173

print(island_countries) # {"CK", "NF", "SB", "TC", "VI", ...}

174

175

# Case-sensitive exact match

176

code = countries.by_name("Macedonia", insensitive=False)

177

178

# Search in different language

179

with translation.override('de'):

180

code = countries.by_name("Deutschland", language='de')

181

```

182

183

## Configuration

184

185

### Custom Countries Lists

186

187

Create specialized Countries instances with custom configurations:

188

189

```python

190

from django_countries import Countries

191

192

# Custom instance with specific countries only

193

eu_countries = Countries()

194

eu_countries.only = ["DE", "FR", "IT", "ES", "NL", "BE"]

195

196

# Custom instance with overrides

197

custom_countries = Countries()

198

custom_countries.override = {"US": "America", "GB": "Britain"}

199

custom_countries.common_names = True

200

```

201

202

### Countries Configuration Options

203

204

Configure via Django settings or Countries instance attributes:

205

206

```python

207

# Via Django settings

208

COUNTRIES_OVERRIDE = {

209

"US": "America",

210

"GB": "Britain",

211

"AU": None # Exclude Australia

212

}

213

214

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

215

216

COUNTRIES_FIRST = ["US", "CA"] # Show these first

217

COUNTRIES_FIRST_REPEAT = True # Repeat in main list

218

COUNTRIES_FIRST_BREAK = "-------" # Separator after first countries

219

COUNTRIES_FIRST_SORT = True # Sort first countries

220

221

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

222

```

223

224

### Accessing Configuration

225

226

```python

227

from django_countries import countries

228

229

# Access configuration

230

print(countries.get_option("first")) # ["US", "CA"]

231

print(countries.get_option("common_names")) # True

232

print(countries.get_option("override")) # {"US": "America", ...}

233

```

234

235

## Translation Support

236

237

### Language-Specific Names

238

239

```python

240

from django.utils.translation import override

241

242

# Get names in different languages

243

with override('es'):

244

print(countries.name("US")) # "Estados Unidos"

245

246

with override('fr'):

247

print(countries.name("US")) # "États-Unis"

248

249

# Find by translated name

250

with override('de'):

251

code = countries.by_name("Deutschland") # "DE"

252

```

253

254

### Translation Context Management

255

256

```python

257

from django_countries import no_translation_fallback

258

259

# Disable translation fallback

260

with no_translation_fallback():

261

# Only show translations, no fallback to English

262

country_name = countries.name("DE")

263

```

264

265

## Country Data Access

266

267

### Alternative Codes Access

268

269

```python

270

# Access alternative code mappings

271

alt_codes = countries.alt_codes["US"]

272

print(alt_codes.alpha3) # "USA"

273

print(alt_codes.numeric) # 840

274

275

# IOC code mappings

276

ioc_codes = countries.ioc_codes["US"] # "USA"

277

```

278

279

### Historical Names

280

281

```python

282

# Access shadowed/historical names

283

shadowed = countries.shadowed_names.get("CZ", [])

284

# May include historical names like "Czech Republic"

285

```

286

287

## Types

288

289

```python { .api }

290

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

291

from django_stubs_ext import StrPromise

292

293

CountryCode = Union[str, int, None]

294

CountryName = Union[StrPromise, ComplexCountryName]

295

296

class CountryTuple(NamedTuple):

297

code: str

298

name: str

299

300

def __repr__(self) -> str:

301

"""Display as standard tuple for template compatibility."""

302

303

class AltCodes(NamedTuple):

304

alpha3: str

305

numeric: Optional[int]

306

307

class ComplexCountryName(TypedDict):

308

name: StrPromise

309

names: List[StrPromise]

310

alpha3: str

311

numeric: int

312

ioc_code: str

313

```