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

Overview

Django Countries

PyPI version Build status Coverage status

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, 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.

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.
ioc_code
The three letter International Olympic Committee country code.

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(f"{name} ({code})")
...
Afghanistan (AF)
Åland Islands (AX)
Albania (AL)

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

Template Tags

If you have your country code stored in a different place than a CountryField you can use the template tag to get a Country object and have access to all of its properties:

{% load countries %}
{% get_country 'BR' as country %}
{{ country.name }}

If you need a list of countries, there's also a simple tag for that:

{% load countries %}
{% get_countries as countries %}
<select>
{% for country in countries %}
    <option value="{{ country.code }}">{{ country.name }}</option>
{% endfor %}
</select>

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. The values can also use a more complex dictionary format.

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:

from django.utils.translation import gettext_lazy as _

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, 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',
    'GB',
    ('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.

If you want to sort these initial countries too, set the COUNTRIES_FIRST_SORT setting to True.

By default, these initial 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()

Complex dictionary format

For COUNTRIES_ONLY and COUNTRIES_OVERRIDE, you can also provide a dictionary rather than just a translatable string for the country name.

The options within the dictionary are:

name or names (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 using COUNTRIES_FIRST or the Country.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 (or None to 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).

Country object external plugins

Other Python packages can add attributes to the Country object by using entry points in their setup script.

For example, you could create a django_countries_phone package which had a with the following entry point in the setup.py file. The entry point name (phone) will be the new attribute name on the Country object. The attribute value will be the return value of the get_phone function (called with the Country instance as the sole argument).

setup(
    ...
    entry_points={
        'django_countries.Country': 'phone = django_countries_phone.get_phone'
    },
    ...
)

Django Rest Framework

Django Countries ships with a CountryFieldMixin to make the CountryField model field compatible with DRF serializers. Use the following mixin with your model serializer:

from django_countries.serializers import CountryFieldMixin

class CountrySerializer(CountryFieldMixin, serializers.ModelSerializer):

    class Meta:
        model = models.Person
        fields = ('name', 'email', 'country')

This mixin handles both standard and multi-choice country fields.

Django Rest Framework field

For lower level use (or when not dealing with model fields), you can use the included CountryField serializer field. For example:

from django_countries.serializer_fields import CountryField

class CountrySerializer(serializers.Serializer):
    country = CountryField()

You can optionally instantiate the field with the countries argument to specify a custom Countries instance.

REST output format

By default, the field will output just the country code. To output the full country name instead, instanciate the field with name_only=True.

If you would rather have more verbose output, instantiate the field with country_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 the country_dict argument's value.

OPTIONS request

When you request OPTIONS against a resource (using the DRF metadata 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"
      }
    ]
  }
}

GraphQL

A Country graphene object type is included that can be used when generating your schema.

import graphene
from graphene_django.types import DjangoObjectType
from django_countries.graphql.types import Country

class Person(ObjectType):
    country = graphene.Field(Country)

    class Meta:
        model = models.Person
        fields = ["name", "country"]

The object type has the following fields available:

  • name for the full country name
  • code for the ISO 3166-1 two character country code
  • alpha3 for the ISO 3166-1 three character country code
  • numeric for the ISO 3166-1 numeric country code
  • iocCode for the International Olympic Committee country code
ColoringMapAlgorithm-CSP- - Graphical Coloring of Countries with Condition Satisfaction Algorithm

ColoringMapAlgorithm-CSP- Condition Satisfaction Algorithm Output Condition

Kerem TAN 2 Jan 10, 2022
GeoNode is an open source platform that facilitates the creation, sharing, and collaborative use of geospatial data.

Table of Contents What is GeoNode? Try out GeoNode Install Learn GeoNode Development Contributing Roadmap Showcase Most useful links Licensing What is

GeoNode Development Team 1.2k Dec 26, 2022
Download and process satellite imagery in Python using Sentinel Hub services.

Description The sentinelhub Python package allows users to make OGC (WMS and WCS) web requests to download and process satellite images within your Py

Sentinel Hub 659 Dec 23, 2022
ArcGIS Python Toolbox for WhiteboxTools

WhiteboxTools-ArcGIS ArcGIS Python Toolbox for WhiteboxTools. This repository is related to the ArcGIS Python Toolbox for WhiteboxTools, which is an A

Qiusheng Wu 190 Dec 30, 2022
A package to fetch sentinel 2 Satellite data from Google.

Sentinel 2 Data Fetcher Installation Create a Virtual Environment and activate it. python3 -m venv venv . venv/bin/activate Install the Package via pi

1 Nov 18, 2021
Geodata extensions for Django REST Framework

Django-Spillway Django and Django REST Framework integration of raster and feature based geodata. Spillway builds on the immensely marvelous Django RE

Brian Galey 62 Jan 04, 2023
Python script that can be used to generate latitude/longitude coordinates for GOES-16 full-disk extent.

goes-latlon Python script that can be used to generate latitude/longitude coordinates for GOES-16 full-disk extent. 🌎 🛰️ The grid files can be acces

Douglas Uba 3 Apr 06, 2022
Get Landsat surface reflectance time-series from google earth engine

geextract Google Earth Engine data extraction tool. Quickly obtain Landsat multispectral time-series for exploratory analysis and algorithm testing On

Loïc Dutrieux 50 Dec 15, 2022
Python bindings and utilities for GeoJSON

geojson This Python library contains: Functions for encoding and decoding GeoJSON formatted data Classes for all GeoJSON Objects An implementation of

Jazzband 765 Jan 06, 2023
PySAL: Python Spatial Analysis Library Meta-Package

Python Spatial Analysis Library PySAL, the Python spatial analysis library, is an open source cross-platform library for geospatial data science with

Python Spatial Analysis Library 1.1k Dec 18, 2022
Example of animated maps in matplotlib + geopandas using entire time series of congressional district maps from UCLA archive. rendered, interactive version below

Example of animated maps in matplotlib + geopandas using entire time series of congressional district maps from UCLA archive. rendered, interactive version below

Apoorva Lal 5 May 18, 2022
GebPy is a Python-based, open source tool for the generation of geological data of minerals, rocks and complete lithological sequences.

GebPy is a Python-based, open source tool for the generation of geological data of minerals, rocks and complete lithological sequences. The data can be generated randomly or with respect to user-defi

Maximilian Beeskow 16 Nov 29, 2022
Geocode rows in a SQLite database table

Geocode rows in a SQLite database table

Chris Amico 225 Dec 08, 2022
Simulation and Parameter Estimation in Geophysics

Simulation and Parameter Estimation in Geophysics - A python package for simulation and gradient based parameter estimation in the context of geophysical applications.

SimPEG 390 Dec 15, 2022
This is a simple python code to get IP address and its location using python

IP address & Location finder @DEV/ED : Pavan Ananth Sharma Dependencies: ip2geotools Note: use pip install ip2geotools to install this in your termin

Pavan Ananth Sharma 2 Jul 05, 2022
Xarray backend to Copernicus Sentinel-1 satellite data products

xarray-sentinel WARNING: this product is a "technology preview" / pre-Alpha Xarray backend to explore and load Copernicus Sentinel-1 satellite data pr

B-Open 191 Dec 15, 2022
Tool to display your current position and angle above your radar

🛠 Tool to display your current position and angle above your radar. As a response to the CS:GO Update on 1.2.2022, which makes cl_showpos a cheat-pro

Miko 6 Jan 04, 2023
Spectral decomposition for characterizing long-range interaction profiles in Hi-C maps

Inspectral Spectral decomposition for characterizing long-range interaction prof

Nezar Abdennur 6 Dec 13, 2022
Platform for building statistical models of cities and regions

UrbanSim UrbanSim is a platform for building statistical models of cities and regions. These models help forecast long-range patterns in real estate d

Urban Data Science Toolkit 419 Dec 30, 2022
Use Mapbox GL JS to visualize data in a Python Jupyter notebook

Location Data Visualization library for Jupyter Notebooks Library documentation at https://mapbox-mapboxgl-jupyter.readthedocs-hosted.com/en/latest/.

Mapbox 620 Dec 15, 2022