Django Countries

A Django application that provides country choices for use with forms, flag icons static files, and a country field for models.

Installation

  1. pip install django-countries
  2. Add django_countries to INSTALLED_APPS

For more accurate sorting of translated country names, install the optional pyuca package.

CountryField

A country field for Django models that provides all ISO 3166-1 countries as choices.

CountryField is based on Django's CharField, providing choices corresponding to the official ISO 3166-1 list of countries (with a default max_length of 2).

Consider the following model using a CountryField:

from django.db import models
from django_countries.fields import CountryField

class Person(models.Model):
    name = models.CharField(max_length=100)
    country = CountryField()

Any Person instance will have a country attribute that you can use to get details of the person's country:

>>> person = Person(name='Chris', country='NZ')
>>> person.country
Country(code='NZ')
>>> person.country.name
'New Zealand'
>>> person.country.flag
'/static/flags/nz.gif'

This object (person.country in the example) is a Country instance, which is described below.

Use blank_label to set the label for the initial blank choice shown in forms:

country = CountryField(blank_label='(select country)')

Multi-choice

This field can also allow multiple selections of countries (saved as a comma separated string). The field will always output a list of countries in this mode. For example:

class Incident(models.Model):
    title = models.CharField(max_length=100)
    countries = CountryField(multiple=True)

>>> for country in Incident.objects.get(title='Pavlova dispute').countries:
...     print(country.name)
Australia
New Zealand

The Country object

An object used to represent a country, instanciated with a two character country code, three character code, or numeric code.

It can be compared to other objects as if it was a string containing the country code and when evaluated as text, returns the country code.

name

Contains the full country name.

flag

Contains a URL to the flag. If you page could have lots of different flags then consider using flag_css instead to avoid excessive HTTP requests.

flag_css

Output the css classes needed to display an HTML element as the correct flag from within a single sprite image that contains all flags. For example:

<link rel="stylesheet" href="{% static 'flags/sprite.css' %}">
<i class="{{ country.flag_css }}"></i>

For multiple flag resolutions, use sprite-hq.css instead and add the flag2x, flag3x, or flag4x class. For example:

<link rel="stylesheet" href="{% static 'flags/sprite-hq.css' %}">
Normal: <i class="{{ country.flag_css }}"></i>
Bigger: <i class="flag2x {{ country.flag_css }}"></i>

You might also want to consider using aria-label for better accessibility:

<i class="{{ country.flag_css }}"
    aria-label="{% blocktrans with country_code=country.code %}
        {{ country_code }} flag
    {% endblocktrans %}"></i>

unicode_flag
A unicode glyph for the flag for this country. Currently well-supported in iOS and OS X. See https://en.wikipedia.org/wiki/Regional_Indicator_Symbol for details.
code
The two letter country code for this country.
alpha3
The three letter country code for this country.
numeric
The numeric country code for this country (as an integer).
numeric_padded
The numeric country code as a three character 0-padded string.

CountrySelectWidget

A widget is included that can show the flag image after the select box (updated with JavaScript when the selection changes).

When you create your form, you can use this custom widget like normal:

from django_countries.widgets import CountrySelectWidget

class PersonForm(forms.ModelForm):
    class Meta:
        model = models.Person
        fields = ('name', 'country')
        widgets = {'country': CountrySelectWidget()}

Pass a layout text argument to the widget to change the positioning of the flag and widget. The default layout is:

'{widget}<img class="country-select-flag" id="{flag_id}" style="margin: 6px 4px 0" src="{country.flag}">'

Custom forms

If you want to use the countries in a custom form, use the model field's custom form field to ensure the translatable strings for the country choices are left lazy until the widget renders:

from django_countries.fields import CountryField

class CustomForm(forms.Form):
    country = CountryField().formfield()

Use CountryField(blank=True) for non-required form fields, and CountryField(blank_label='(Select country)') to use a custom label for the initial blank option.

You can also use the CountrySelectWidget as the widget for this field if you want the flag image after the select box.

Get the countries from Python

Use the django_countries.countries object instance as an iterator of ISO 3166-1 country codes and names (sorted by name).

For example:

>>> from django_countries import countries
>>> dict(countries)['NZ']
'New Zealand'

>>> for code, name in list(countries)[:3]:
...     print("{name} ({code})".format(name=name, code=code))
...
Afghanistan (AF)
Ă…land Islands (AX)
Albania (AL)

Country names are translated using Django's standard ugettext. If you would like to help by adding a translation, please visit https://www.transifex.com/projects/p/django-countries/

GitHub