Skip to main content

Provides a country field for Django models.

Project description

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

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)')

The Country object

An object used to represent a country, instanciated with a two character country 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.

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}">'

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/

Customization

Customize the country list

Country names are taken from the official ISO 3166-1 list. If your project requires the use of alternative names, the inclusion or exclusion of specific countries then use the COUNTRIES_OVERRIDE setting.

A dictionary of names to override the defaults.

Note that you will need to handle translation of customised country names.

Setting a country’s name to None will exclude it from the country list. For example:

COUNTRIES_OVERRIDE = {
    'NZ': _('Middle Earth'),
    'AU': None
}

If you have a specific list of countries that should be used, use COUNTRIES_ONLY:

COUNTRIES_ONLY = ['NZ', 'AU']

or to specify your own country names, use a dictionary or two-tuple list (string items will use the standard country name):

COUNTRIES_ONLY = [
    'US',
    'UK'
    ('NZ', _('Middle Earth')),
    ('AU', _('Desert')),
]

Show certain countries first

Provide a list of country codes as the COUNTRIES_FIRST setting and they will be shown first in the countries list (in the order specified) before all the alphanumerically sorted countries.

By default, these ‘first’ countries are not repeated again in the alphanumerically sorted list. If you would like them to be repeated, set the COUNTRIES_FIRST_REPEAT setting to True.

Finally, you can optionally separate these ‘first’ countries with an empty choice by providing the choice label as the COUNTRIES_FIRST_BREAK setting.

Customize the flag URL

The COUNTRIES_FLAG_URL setting can be used to set the url for the flag image assets. It defaults to:

COUNTRIES_FLAG_URL = 'flags/{code}.gif'

The URL can be relative to the STATIC_URL setting, or an absolute URL.

The location is parsed using Python’s string formatting and is passed the following arguments:

  • code

  • code_upper

For example: COUNTRIES_FLAG_URL = 'flags/16x10/{code_upper}.png'

No checking is done to ensure that a static flag actually exists.

Alternatively, you can specify a different URL on a specific CountryField:

class Person(models.Model):
    name = models.CharField(max_length=100)
    country = CountryField(
        countries_flag_url='//flags.example.com/{code}.png')

Single field customization

To customize an individual field, rather than rely on project level settings, create a Countries subclass which overrides settings.

To override a setting, give the class an attribute matching the lowercased setting without the COUNTRIES_ prefix.

Then just reference this class in a field. For example, this CountryField uses a custom country list that only includes the G8 countries:

from django_countries import Countries

class G8Countries(Countries):
    only = [
        'CA', 'FR', 'DE', 'IT', 'JP', 'RU', 'GB',
        ('EU', _('European Union'))
    ]

class Vote(models.Model):
    country = CountryField(countries=G8Countries)
    approve = models.BooleanField()

Change Log

This log shows interesting changes that happen for each version, latest versions first. It can be assumed that translations have been updated each release (and any new translations added).

Version 3.3 (30 Mar 2015)

  • Add the attributes to Countries class that can override the default settings.

  • CountriesField can now be passed a custom countries subclass to use, which combined with the previous change allows for different country choices for different fields.

  • Allow COUNTRIES_ONLY to also accept just country codes in its list (rather than only two-tuples), looking up the translatable country name from the full country list.

  • Fix Montenegro flag size (was 12px high rather than the standard 11px).

  • Fix outdated ISO country name formatting for Bolivia, Gambia, Holy See, Iran, Micronesia, and Venezuela.

Version 3.2 (24 Feb 2015)

  • Fixes initial iteration failing for a fresh Countries object.

  • Fix widget’s flag URLs (and use ensure widget is HTML encoded safely).

  • Add countries.by_name(country, language='en') method, allowing lookup of a country code by its full country name. Thanks Josh Schneier.

Version 3.1 (15 Jan 2015)

  • Start change log :)

  • Add a COUNTRIES_FIRST setting (and some other related ones) to allow for specific countries to be shown before the entire alphanumeric list.

  • Add a blank_label argument to CountryField to allow customization of the label shown in the initial blank choice shown in the select widget.

Version 3.1.1 (15 Jan 2015)

  • Packaging fix (CHANGES.rst wasn’t in the manifest)

Version 3.0 (22 Oct 2014)

Django supported versions are now 1.4 (LTS) and 1.6+

  • Add COUNTRIES_ONLY setting to restrict to a specific list of countries.

  • Optimize country name translations to avoid exessive translation calls that were causing a notable performance impact.

  • PyUCA integration, allowing for more accurate sorting across all locales. Also, a better sorting method when PyUCA isn’t installed.

  • Better tests (now at 100% test coverage).

  • Add a COUNTRIES_FLAG_URL setting to allow custom flag urls.

  • Support both IOC and numeric country codes, allowing more flexible lookup of countries and specific code types.

  • Field descriptor now returns None if no country matches (reverted in v3.0.1)

Version 3.0.1 (27 Oct 2014)

  • Revert descriptor to always return a Country object.

  • Fix the CountryField widget choices appearing empty due to a translation change in v3.0.

Version 3.0.2 (29 Dec 2014)

  • Fix CountrySelectWidget failing when used with a model form that is passed a model instance.

Version 2.1 (24 Mar 2014)

  • Add IOC (3 letter) country codes.

  • Fix bug when loading fixtures.

Version 2.1.1 (28 Mar 2014)

  • Fix issue with translations getting evaluated early.

Version 2.1.2 (28 Mar 2014)

  • Fix Python 3 compatibility.

Version 2.0 (18 Feb 2014)

This is the first entry to the change log. The previous version was 1.5, released 19 Nov 2012.

  • Optimized flag images, adding flags missing from original source.

  • Better storage of settings and country list.

  • New country list format for fields.

  • Better tests.

  • Changed COUNTRIES_FLAG_STATIC setting to COUNTRIES_FLAG_URL.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-countries-3.3.tar.gz (245.7 kB view details)

Uploaded Source

File details

Details for the file django-countries-3.3.tar.gz.

File metadata

File hashes

Hashes for django-countries-3.3.tar.gz
Algorithm Hash digest
SHA256 11827070ebcf201d22ea531aa90e18146ca89580bd1897a132eb8afbc6b35b7d
MD5 a981d1ae636ef8b5f05a0c73f7a7806e
BLAKE2b-256 a4867948d078aa5220479c89480b83dfca449d627cdefcf1d70adcfbe9a21dc0

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page