Django Countries
django-countries is a Django application that provides a `CountryField` for models, offering all ISO 3166-1 countries as choices. It includes utilities for forms, flag icons as static files, and integrates with Django's internationalization system for translated country names. The current version is 8.2.0, and it maintains an active release cadence with regular updates.
Warnings
- breaking Version 8.0.0 inadvertently dropped Python 3.7 support without a major version bump, leading to yanked releases. Users on Python 3.7 should use a version prior to 8.0.0 or upgrade their Python environment.
- gotcha When overriding country definitions using `COUNTRIES_OVERRIDE` in `settings.py`, be careful with dictionary syntax, particularly trailing commas which can cause unexpected issues or silent failures depending on Python version and context.
- gotcha `django-countries` is designed specifically for managing country selections. For more complex geographical data, such as cities, regions, or subregions, consider using dedicated libraries like `django-cities-light` or implementing a custom solution.
- gotcha When retrieving a `CountryField` value, it returns a `Country` object. To access the full country name or other attributes, use `instance.country.name` or `instance.country.code`. Simply using `instance.country` in some contexts (like template forms without explicit rendering) might default to displaying the country code.
Install
-
pip install django-countries
Imports
- CountryField
from django_countries.fields import CountryField
- countries
from django_countries import countries
Quickstart
# settings.py
INSTALLED_APPS = [
# ...
'django_countries',
]
# models.py (in your app)
from django.db import models
from django_countries.fields import CountryField
class Person(models.Model):
name = models.CharField(max_length=100)
country = CountryField()
# Example usage in a Django shell
# >>> from myapp.models import Person
# >>> person = Person.objects.create(name="Chris", country="NZ")
# >>> person.country
# Country(code='NZ')
# >>> person.country.name
# 'New Zealand'
# >>> person.country.flag
# '/static/flags/nz.gif'