Package: django-countries
Django CountriesA Django application that provides country choices for use with forms, flag
icons static files, and a country field for models.Country names are translated using Django’s standardgettext. If you would
like to help by adding a translation, please visithttps://www.transifex.com/smileychris/django-countries/InstallationCountryFieldMulti-choiceTheCountryobjectCountrySelectWidgetCustom formsGet the countries from PythonTemplate TagsCustomizationCustomize the country listShow certain countries firstCustomize the flag URLSingle field customizationComplex dictionary formatCountryobject external pluginsDjango Rest FrameworkDjango Rest Framework fieldREST output formatOPTIONS requestGraphQLInstallationpip installdjango-countriesFor more accurate sorting of translated country names, install it with the
optionalpyucapackage:pip installdjango-countries[pyuca]Adddjango_countriestoINSTALLED_APPSCountryFieldA country field for Django models that provides all ISO 3166-1 countries as
choices.CountryFieldis based on Django’sCharField, providing choices
corresponding to the official ISO 3166-1 list of countries (with a defaultmax_lengthof 2).Consider the following model using aCountryField:fromdjango.dbimportmodelsfromdjango_countries.fieldsimportCountryFieldclassPerson(models.Model):name=models.CharField(max_length=100)country=CountryField()AnyPersoninstance will have acountryattribute that you can use to
get details of the person’s country:>>>person=Person(name="Chris",country="NZ")>>>person.countryCountry(code='NZ')>>>person.country.name'New Zealand'>>>person.country.flag'/static/flags/nz.gif'This object (person.countryin the example) is aCountryinstance,
which is described below.Useblank_labelto set the label for the initial blank choice shown in
forms:country=CountryField(blank_label="(select country)")You can filter using the full English country names in addition to country
codes, even though only the country codes are stored in the database by using
the queryset lookupscontains,startswith,endswith,regex, or
their case insensitive versions. Use__nameor__inamefor theexact/iexactequivalent:>>>Person.objects.filter(country__name="New Zealand").count()1>>>Person.objects.filter(country__icontains="zealand").count()1Multi-choiceThis 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:classIncident(models.Model):title=models.CharField(max_length=100)countries=CountryField(multiple=True)>>>forcountryinIncident.objects.get(title="Pavlova dispute").countries:...print(country.name)AustraliaNewZealandBy default, countries are stored sorted for data consistency, and any
duplicates are removed. These behaviours can be overridden by using the field
argumentsmultiple_sort=Falseandmultiple_unique=Falserespectively.TheCountryobjectAn object used to represent a country, instantiated 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.nameContains the full country name.flagContains a URL to the flag. If you page could have lots of different flags
then consider usingflag_cssinstead to avoid excessive HTTP requests.flag_cssOutput 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, usesprite-hq.cssinstead and add theflag2x,flag3x, orflag4xclass. 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 usingaria-labelfor better
accessibility:<i class="{{country.flag_css}}"
    aria-label="{%blocktranswithcountry_code=country.code%}{{country_code}}flag{%endblocktrans%}"></i>unicode_flagA unicode glyph for the flag for this country. Currently well-supported in
iOS and OS X. Seehttps://en.wikipedia.org/wiki/Regional_Indicator_Symbolfor details.codeThe two letter country code for this country.alpha3The three letter country code for this country.numericThe numeric country code for this country (as an integer).numeric_paddedThe numeric country code as a three character 0-padded string.ioc_codeThe three letter International Olympic Committee country code.CountrySelectWidgetA 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:fromdjango_countries.widgetsimportCountrySelectWidgetclassPersonForm(forms.ModelForm):classMeta:model=models.Personfields=("name","country")widgets={"country":CountrySelectWidget()}Pass alayouttext 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 formsIf 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:fromdjango_countries.fieldsimportCountryFieldclassCustomForm(forms.Form):country=CountryField().formfield()UseCountryField(blank=True)for non-required form fields, andCountryField(blank_label="(Selectcountry)")to use a custom label for the
initial blank option.You can also use theCountrySelectWidgetas the widget for this field if you
want the flag image after the select box.Get the countries from PythonUse thedjango_countries.countriesobject instance as an iterator of ISO
3166-1 country codes and names (sorted by name).For example:>>>fromdjango_countriesimportcountries>>>dict(countries)["NZ"]'New Zealand'>>>forcode,nameinlist(countries)[:3]:...print(f"{name}({code})")...Afghanistan(AF)ÅlandIslands(AX)Albania(AL)Template TagsIf you have your country code stored in a different place than aCountryFieldyou can use the template tag to get aCountryobject and
have access to all of its properties:{%loadcountries%}{%get_country'BR'ascountry%}{{country.name}}If you need a list of countries, there’s also a simple tag for that:{%loadcountries%}{%get_countriesascountries%}<select>{%forcountryincountries%}<option value="{{country.code}}">{{country.name}}</option>{%endfor%}</select>CustomizationCustomize the country listCountry names are taken from the official ISO 3166-1 list, with some country
names being replaced with their more common usage (such as “Bolivia” instead
of “Bolivia, Plurinational State of”).To retain the official ISO 3166-1 naming for all fields, set theCOUNTRIES_COMMON_NAMESsetting toFalse.If your project requires the use of alternative names, the inclusion or
exclusion of specific countries then set theCOUNTRIES_OVERRIDEsetting to
a dictionary of names which override the defaults. The values can also use a
morecomplex dictionary format.Note that you will need to handle translation of customised country names.Setting a country’s name toNonewill exclude it from the country list.
For example:fromdjango.utils.translationimportgettext_lazyas_COUNTRIES_OVERRIDE={"NZ":_("Middle Earth"),"AU":None,"US":{"names":[_("United States of America"),_("America"),],},}If you have a specific list of countries that should be used, useCOUNTRIES_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","GB",("NZ",_("Middle Earth")),("AU",_("Desert")),]Show certain countries firstProvide a list of country codes as theCOUNTRIES_FIRSTsetting and they
will be shown first in the countries list (in the order specified) before all
the alphanumerically sorted countries.If you want to sort these initial countries too, set theCOUNTRIES_FIRST_SORTsetting toTrue.By default, these initial countries are not repeated again in the
alphanumerically sorted list. If you would like them to be repeated, set theCOUNTRIES_FIRST_REPEATsetting toTrue.Finally, you can optionally separate these “first” countries with an empty
choice by providing the choice label as theCOUNTRIES_FIRST_BREAKsetting.Customize the flag URLTheCOUNTRIES_FLAG_URLsetting 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:codecode_upperFor 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 specificCountryField:classPerson(models.Model):name=models.CharField(max_length=100)country=CountryField(countries_flag_url="//flags.example.com/{code}.png")Single field customizationTo customize an individual field, rather than rely on project level settings,
create aCountriessubclass which overrides settings.To override a setting, give the class an attribute matching the lowercased
setting without theCOUNTRIES_prefix.Then just reference this class in a field. For example, thisCountryFielduses a custom country list that only includes the G8 countries:fromdjango_countriesimportCountriesclassG8Countries(Countries):only=["CA","FR","DE","IT","JP","RU","GB",("EU",_("European Union"))]classVote(models.Model):country=CountryField(countries=G8Countries)approve=models.BooleanField()Complex dictionary formatForCOUNTRIES_ONLYandCOUNTRIES_OVERRIDE, you can also provide a
dictionary rather than just a translatable string for the country name.The options within the dictionary are:nameornames(required)Either a single translatable name for this country or a list of multiple
translatable names. If using multiple names, the first name takes preference
when usingCOUNTRIES_FIRSTor theCountry.name.alpha3(optional)An ISO 3166-1 three character code (or an empty string to nullify an existing
code for this country.numeric(optional)An ISO 3166-1 numeric country code (orNoneto nullify an existing code
for this country. The numeric codes 900 to 999 are left available by the
standard for user-assignment.ioc_code(optional)The country’s International Olympic Committee code (or an empty string to
nullify an existing code).Countryobject external pluginsOther Python packages can add attributes to theCountryobject by using entry
points in their setup script.For example, you could create adjango_countries_phonepackage which had a
with the following entry point in thesetup.pyfile. The entry point name
(phone) will be the new attribute name on the Country object. The attribute
value will be the return value of theget_phonefunction (called with the
Country instance as the sole argument).setup(...entry_points={"django_countries.Country":"phone = django_countries_phone.get_phone"},...)Django Rest FrameworkDjango Countries ships with aCountryFieldMixinto make theCountryFieldmodel field compatible with DRF serializers. Use the following
mixin with your model serializer:fromdjango_countries.serializersimportCountryFieldMixinclassCountrySerializer(CountryFieldMixin,serializers.ModelSerializer):classMeta:model=models.Personfields=("name","email","country")This mixin handles both standard andmulti-choicecountry fields.Django Rest Framework fieldFor lower level use (or when not dealing with model fields), you can use the
includedCountryFieldserializer field. For example:fromdjango_countries.serializer_fieldsimportCountryFieldclassCountrySerializer(serializers.Serializer):country=CountryField()You can optionally instantiate the field with thecountriesargument to
specify a customCountriesinstance.REST output formatBy default, the field will output just the country code. To output the full
country name instead, instantiate the field withname_only=True.If you would rather have more verbose output, instantiate the field withcountry_dict=True, which will result in the field having the following
output structure:{"code":"NZ","name":"New Zealand"}Either the code or this dict output structure are acceptable as input
irregardless of thecountry_dictargument’s value.OPTIONS requestWhen you request OPTIONS against a resource (using the DRFmetadata support)
the countries will be returned in the response as choices:OPTIONS /api/address/ HTTP/1.1

HTTP/1.1 200 OK
Content-Type: application/json
Allow: GET, POST, HEAD, OPTIONS

{
"actions": {
  "POST": {
    "country": {
    "type": "choice",
    "label": "Country",
    "choices": [
      {
        "display_name": "Australia",
        "value": "AU"
      },
      [...]
      {
        "display_name": "United Kingdom",
        "value": "GB"
      }
    ]
  }
}GraphQLACountrygraphene object type is included that can be used when generating
your schema.importgraphenefromgraphene_django.typesimportDjangoObjectTypefromdjango_countries.graphql.typesimportCountryclassPerson(ObjectType):country=graphene.Field(Country)classMeta:model=models.Personfields=["name","country"]The object type has the following fields available:namefor the full country namecodefor the ISO 3166-1 two character country codealpha3for the ISO 3166-1 three character country codenumericfor the ISO 3166-1 numeric country codeiocCodefor the International Olympic Committee country codeChange LogThis 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.7.5.1 (1 February 2023)MakeCountryFieldqueryset filters also work with country codes in
addition to names.Switch topyproject.tomlrather thansetup.pyto fix installation
issues with pip 23.0+.7.5 (12 December 2022)Rename Turkey to Türkiye.A change in v7.4 introduced multi-choice countries being stored sorted and
deduplicated. This remains the default behaviour going forwards, but these
can now be overridden via arguments on theCountryField.Improve translation fallback handling, fixing a threading race condition that
could cause odd translation issues. Thanks to Jan Wróblewski and Antoine
Fontaine for their help in resolving this.
This also fixes translation issues with older Python 3.6/3.7 versions.Add Python 3.11, drop Python 3.6 and Django 2.2 support.7.4.2 (10 October 2022)Fix error when usingUSE_I18N = False.7.4.1 (7 October 2022)Fix broken translations due to last common country names fix.7.4 (7 October 2022)Fixed Traditional Chinese translation (needed to belocale/zh_Hant).Update flag of Honduras.Add Django 4.0 and 4.1 to the test matrix, dropping 3.0 and 3.1Add Django Rest Framework 3.13 and 3.14, dropping 3.11.Multi-choice countries are now stored sorted and with duplicates stripped.
Thanks flbraun and Jens Diemer!Fix common country names not being honoured in non-English translations (only
fixed for Python 3.8+).7.3.2 (4 March 2022)Fix slowdown introduced in v7.3 caused by always using country name lookups
for field comparisons.filter(country="NewZealand")will no longer match
now, but instead new__nameand__inamefilters have been added to
achieve this.7.3.1 (1 March 2022)Typing compatibility fixes for Python <3.9.7.3 (28 February 2022)Make full English country names work in database lookups, for example,Person.objects.filter(country__icontains="zealand").7.2.1 (11 May 2021)Fix Latin translations.7.2 (10 May 2021)Allow the character field to work with custom country codes that are not 2
characters (such as “GB-WLS”).Fix compatibility withdjango-migrations-ignore-attrslibrary.7.1 (17 March 2021)Allow customising thestr_attrof Country objects returned from a
CountryField via a newcountries_str_attrkeyword argument (thanks C.
Quentin).Addpyucaas an extra dependency, so that it can be installed likepip installdjango-countries[pyuca].Add Django 3.2 support.7.0 (5 December 2020)Addname_onlyas an option to the Django Rest Framework serializer field
(thanks Miguel Marques).Add in Python typing.Add Python 3.9, Django 3.1, and Django Rest Framework 3.12 support.Drop Python 3.5 support.Improve IOC code functionality, allowing them to be overridden inCOUNTRIES_OVERRIDEusing the complex dictionary format.6.1.3 (18 August 2020)Update flag of Mauritania.Add flag for Kosovo (under its temporary code of XK).6.1.2 (26 March 2020)Fix Python 3.5 syntax error (no f-strings just yet…).6.1.1 (26 March 2020)Change ISO country import so that “Falkland Islands  [Malvinas]” => “Falkland Islands (Malvinas)”.6.1 (20 March 2020)Add a GraphQL object type for a djangoCountryobject.6.0 (28 February 2020)Make DRF CountryField respectblank=False. This is a backwards incompatible change since blank input will now
return a validation error (unlessblankis explicitly set toTrue).FixCOUNTRIES_OVERRIDEwhen using the complex dictionary format and a single name.Add bandit to the test suite for basic security analysis.Drop Python 2.7 and Python 3.4 support.Add Rest Framework 3.10 and 3.11 to the test matrix, remove 3.8.Fix a memory leak when using PyUCA. Thanks Meiyer (aka interDist)!5.5 (11 September 2019)Django 3.0 compatibility.Plugin system for extending theCountryobject.5.4 (11 August 2019)Renamed Macedonia -> North Macedonia.Fix an outlyingmakemigrationserror.Pulled in new translations which were provided but missing from previous
version.Fixed Simplified Chinese translation (needed to belocale/zh_Hans).Introduce an optional complex format forCOUNTRIES_ONLYandCOUNTRIES_OVERRIDEto allow for multiple names for a country, a custom
three character code, and a custom numeric country code.5.3.3 (16 February 2019)Add test coverage for Django Rest Framework 3.9.5.3.2 (27 August 2018)Tests for Django 2.1 and Django Rest Framework 3.8.5.3.1 (12 June 2018)FixdumpdataandloaddataforCountryField(multiple=True).5.3 (20 April 2018)Iterating aCountriesobject now returns named tuples. This makes things
nicer when using{% get_countries %}or using the country list elsewhere
in your code.5.2 (9 March 2018)Ensure Django 2.1 compatibility forCountrySelectWidget.Fix regression introduced into 5.1 when using Django 1.8 and certain queryset
lookup types (like__in).5.1.1 (31 January 2018)Fix some translations that were included in 5.1 but not compiled.5.1 (30 January 2018)Tests now also cover Django Rest Framework 3.7 and Django 2.0.Allow for creating country fields using (valid) alpha-3 or numeric codes.Fix migration error with blank default (thanks Jens Diemer).Add a{% get_countries %}template tag (thanks Matija Čvrk).5.0 (10 October 2017)No longer allowmultiple=Trueandnull=Truetogether. This causes
problems saving the field, andnullshouldn’t really be used anyway
because the country field is a subclass ofCharField.4.6 (16 June 2017)Add aCountryFieldMixinDjango Rest Framework serializer mixin that
automatically picks the right field type for aCountryField(both single
and multi-choice).Validation for Django Rest Framework field (thanks Simon Meers).Allow case-insensitive.by_name()matching (thanks again, Simon).Ensure a multiple-choiceCountryField.max_lengthis enough to hold all
countries.Fix inefficient pickling of countries (thanks Craig de Stigter for the report
and tests).Stop adding a blank choice when dealing with a multi-choiceCountryField.Tests now cover multiple Django Rest Framework versions (back to 3.3).4.6.1Fix invalid reStructuredText in CHANGES.4.6.2Use transparency layer for flag sprites.4.5 (18 April 2017)Change rest framework field to be based onChoiceField.Allow for the rest framework field to deserialize by full country name
(specifically the English name for now).4.4 (6 April 2017)Fix for broken CountryField on certain models in Django 1.11.
Thanks aktiur for the test case.Update tests to cover Django 1.114.3 (29 March 2017)Handle “Czechia” translations in a nicer way (fall back to “Czech Republic”
until new translations are available).Fix for an import error in Django 1.9+ due to use of non-lazyugettextin
the django-countries custom admin filter.Back to 100% test coverage.4.2 (10 March 2017)Add sprite flag files (andCountry.flag_cssproperty) to help minimize
HTTP requests.4.1 (22 February 2017)Better default Django admin filter when filtering a country field in aModelAdmin.Fix settings to support Django 1.11Fix when using a model instance with a deferred country field.AllowCountryFieldto handle multiple countries at once!Allow CountryField to still work if Deferred.Fix a field with customized country list. Thanks pilmie!4.0 (16 August 2016)Django supported versions are now 1.8+Drop legacy codeFix tests, 100% coverageIOS / OSX unicode flags functionFix widget choices on Django 1.9+AddCOUNTRIES_FIRST_SORT. Thanks Edraak!4.0.1Fix tests forCOUNTRIES_FIRST_SORT(feature still worked, tests didn’t).3.4 (22 October 2015)Extend test suite to cover Django 1.8Fix XSS escaping issue in CountrySelectWidgetCommon name changes: fix typo of Moldova, add United KingdomAdd{% get_country %}template tag.NewCountryFieldDjango Rest Framework serializer field.3.4.1Fix minor packaging error.3.3 (30 Mar 2015)Add the attributes toCountriesclass 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.AllowCOUNTRIES_ONLYto 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.3.2 (24 Feb 2015)Fixes initial iteration failing for a freshCountriesobject.Fix widget’s flag URLs (and use ensure widget is HTML encoded safely).Addcountries.by_name(country,language='en')method, allowing lookup of
a country code by its full country name. Thanks Josh Schneier.3.1 (15 Jan 2015)Start change log :)Add aCOUNTRIES_FIRSTsetting (and some other related ones) to allow for
specific countries to be shown before the entire alphanumeric list.Add ablank_labelargument toCountryFieldto allow customization of
the label shown in the initial blank choice shown in the select widget.3.1.1 (15 Jan 2015)Packaging fix (CHANGES.rstwasn’t in the manifest)3.0 (22 Oct 2014)Django supported versions are now 1.4 (LTS) and 1.6+AddCOUNTRIES_ONLYsetting 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 aCOUNTRIES_FLAG_URLsetting 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 returnsNoneif no country matches (reverted in
v3.0.1)3.0.1 (27 Oct 2014)Revert descriptor to always return a Country object.Fix theCountryFieldwidget choices appearing empty due to a translation
change in v3.0.3.0.2 (29 Dec 2014)FixCountrySelectWidgetfailing when used with a model form that is
passed a model instance.2.1 (24 Mar 2014)Add IOC (3 letter) country codes.Fix bug when loading fixtures.2.1.1 (28 Mar 2014)Fix issue with translations getting evaluated early.2.1.2 (28 Mar 2014)Fix Python 3 compatibility.2.0 (18 Feb 2014)This is the first entry to the change log. The previous 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.ChangedCOUNTRIES_FLAG_STATICsetting toCOUNTRIES_FLAG_URL.