0
# Model Fields
1
2
Django model field for storing country codes with rich Country object functionality. The CountryField provides automatic Country object descriptors, validation, and supports both single and multiple country selection with extensive customization options.
3
4
## Capabilities
5
6
### CountryField
7
8
Django model field that stores country codes as CharField but provides Country objects with full country details including names, flags, and alternative codes.
9
10
```python { .api }
11
class CountryField(models.CharField):
12
def __init__(
13
self,
14
countries=None,
15
countries_flag_url=None,
16
countries_str_attr="code",
17
blank_label=None,
18
multiple=None,
19
multiple_unique=True,
20
multiple_sort=True,
21
**kwargs
22
):
23
"""
24
Django model field for country selection.
25
26
Parameters:
27
- countries: Countries class - Custom countries instance for field
28
- countries_flag_url: str - Custom flag URL pattern override
29
- countries_str_attr: str - Attribute to use for string representation ("code", "name")
30
- blank_label: str - Label to use for blank choice in forms
31
- multiple: bool - Allow multiple country selection
32
- multiple_unique: bool - Ensure unique values in multiple selection
33
- multiple_sort: bool - Sort multiple selected values
34
- **kwargs: Standard CharField arguments (max_length, null, blank, etc.)
35
"""
36
```
37
38
Usage examples:
39
40
```python
41
from django.db import models
42
from django_countries.fields import CountryField
43
44
# Basic usage
45
class Person(models.Model):
46
country = CountryField()
47
48
# With custom options
49
class Organization(models.Model):
50
countries = CountryField(
51
multiple=True,
52
blank_label="(select countries)"
53
)
54
55
# With custom flag URL
56
class Event(models.Model):
57
country = CountryField(countries_flag_url="custom/flags/{code}.png")
58
59
# Using name as string representation
60
class Location(models.Model):
61
country = CountryField(countries_str_attr="name")
62
```
63
64
### Country Object
65
66
Individual country representation automatically provided by CountryField descriptor with access to country metadata and flag URLs.
67
68
```python { .api }
69
class Country:
70
def __init__(
71
self,
72
code: str,
73
flag_url: Optional[str] = None,
74
str_attr: str = "code",
75
custom_countries: Optional[Countries] = None
76
):
77
"""
78
Individual country object with metadata access.
79
80
Parameters:
81
- code: str - Country code (alpha2, alpha3, or numeric)
82
- flag_url: str - Custom flag URL pattern
83
- str_attr: str - Attribute for string representation
84
- custom_countries: Countries - Custom countries instance
85
"""
86
87
@property
88
def name(self) -> str:
89
"""Country name in current language"""
90
91
@property
92
def flag(self) -> str:
93
"""Flag URL based on flag_url pattern"""
94
95
@property
96
def alpha3(self) -> str:
97
"""ISO 3166-1 three letter country code"""
98
99
@property
100
def numeric(self) -> Optional[int]:
101
"""ISO 3166-1 numeric country code"""
102
103
@property
104
def ioc_code(self) -> str:
105
"""International Olympic Committee code"""
106
107
@property
108
def numeric_padded(self) -> Optional[str]:
109
"""ISO 3166-1 numeric country code as zero-padded string"""
110
111
@property
112
def flag_css(self) -> str:
113
"""CSS classes for displaying country flag as sprite"""
114
115
@property
116
def unicode_flag(self) -> str:
117
"""Unicode flag emoji representation"""
118
119
@staticmethod
120
def country_from_ioc(ioc_code: str, flag_url: str = "") -> Optional['Country']:
121
"""Create Country object from IOC code"""
122
123
def __str__(self) -> str:
124
"""String representation based on str_attr"""
125
126
def __eq__(self, other) -> bool:
127
"""Equality comparison with country codes"""
128
129
def __bool__(self) -> bool:
130
"""Boolean conversion - True if valid country code"""
131
```
132
133
Usage examples:
134
135
```python
136
# Accessing country object properties
137
person = Person.objects.get(id=1)
138
print(person.country.name) # "United States"
139
print(person.country.code) # "US"
140
print(person.country.flag) # "/static/flags/us.gif"
141
print(person.country.alpha3) # "USA"
142
print(person.country.numeric) # 840
143
print(person.country.numeric_padded) # "840"
144
print(person.country.flag_css) # "flag-sprite flag-u flag-_s"
145
print(person.country.unicode_flag) # "🇺🇸"
146
147
# Create country from IOC code
148
olympic_country = Country.country_from_ioc("USA")
149
print(olympic_country.code) # "US"
150
151
# Country object comparisons
152
if person.country == "US":
153
print("American person")
154
155
# Multiple countries
156
org = Organization.objects.get(id=1)
157
for country in org.countries:
158
print(f"{country.code}: {country.name}")
159
```
160
161
### Model Field Lookups
162
163
Specialized lookup types for querying countries by name patterns, providing case-sensitive and case-insensitive searches with various matching strategies.
164
165
```python { .api }
166
# Available lookups for CountryField
167
field__name_exact = "United States" # Exact country name match
168
field__name_iexact = "united states" # Case-insensitive exact match
169
field__name_contains = "United" # Country name contains text
170
field__name_icontains = "united" # Case-insensitive contains
171
field__name_startswith = "United" # Country name starts with text
172
field__name_istartswith = "united" # Case-insensitive starts with
173
field__name_endswith = "States" # Country name ends with text
174
field__name_iendswith = "states" # Case-insensitive ends with
175
field__name_regex = r"^United.*" # Regular expression match
176
field__name_iregex = r"^united.*" # Case-insensitive regex match
177
```
178
179
Usage examples:
180
181
```python
182
from myapp.models import Person
183
184
# Find people from countries containing "United"
185
people = Person.objects.filter(country__name_contains="United")
186
187
# Case-insensitive search for countries starting with "united"
188
people = Person.objects.filter(country__name_istartswith="united")
189
190
# Regex search for countries ending with "land"
191
people = Person.objects.filter(country__name_regex=r".*land$")
192
```
193
194
### Custom Countries
195
196
Use custom Countries instances for specialized country lists or configurations per field.
197
198
```python
199
from django_countries import Countries
200
201
# Create custom countries instance
202
eu_countries = Countries()
203
eu_countries.only = ["DE", "FR", "IT", "ES", "NL", "BE"]
204
205
class EuropeanEvent(models.Model):
206
country = CountryField(countries=eu_countries)
207
```
208
209
## Field Configuration
210
211
### Multiple Country Selection
212
213
Enable multiple country selection with validation and sorting options:
214
215
```python
216
class MultiNationalOrg(models.Model):
217
# Allow multiple countries, ensure uniqueness, keep sorted
218
operating_countries = CountryField(
219
multiple=True,
220
multiple_unique=True,
221
multiple_sort=True,
222
blank=True
223
)
224
225
# Multiple countries without sorting
226
regions = CountryField(
227
multiple=True,
228
multiple_sort=False
229
)
230
```
231
232
### Custom Flag URLs
233
234
Configure custom flag image patterns:
235
236
```python
237
class CustomFlagModel(models.Model):
238
# Use PNG flags in custom directory
239
country = CountryField(
240
countries_flag_url="assets/flags/{code_upper}.png"
241
)
242
243
# Use external flag service
244
country2 = CountryField(
245
countries_flag_url="https://flags.example.com/{code}.svg"
246
)
247
```
248
249
The flag URL pattern supports these format variables:
250
- `{code}`: lowercase country code
251
- `{code_upper}`: uppercase country code
252
253
### String Representation
254
255
Control how Country objects render as strings:
256
257
```python
258
class DisplayModel(models.Model):
259
# Display country code (default)
260
country_code = CountryField(countries_str_attr="code")
261
262
# Display country name
263
country_name = CountryField(countries_str_attr="name")
264
265
# Usage
266
obj = DisplayModel(country_code="US", country_name="US")
267
print(obj.country_code) # "US"
268
print(obj.country_name) # "United States"
269
```