././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1712005260.7406936
django-countries-7.6.1/ 0000755 0001750 0001751 00000000000 14602620215 014041 5 ustar 00chris chris ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1712005260.0
django-countries-7.6.1/CHANGES.rst 0000644 0001750 0001751 00000031013 14602620214 015640 0 ustar 00chris chris ==========
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.
7.6.1 (2 April 2024)
====================
- Fix a TypeError when no country is selected, introduced in the Django 5 fix.
7.6 (27 March 2024)
===================
- Replace deprecated ``pkg_resources.iter_entry_points`` with
``importlib_metadata``.
- Support Django 5.0.
7.5.1 (1 February 2023)
=======================
- Make ``CountryField`` queryset filters also work with country codes in
addition to names.
- Switch to ``pyproject.toml`` rather than ``setup.py`` to 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 the ``CountryField``.
- 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 using ``USE_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 be ``locale/zh_Hant``).
- Update flag of Honduras.
- Add Django 4.0 and 4.1 to the test matrix, dropping 3.0 and 3.1
- Add 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="New Zealand")`` will no longer match
now, but instead new ``__name`` and ``__iname`` filters 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 with ``django-migrations-ignore-attrs`` library.
7.1 (17 March 2021)
===================
- Allow customising the ``str_attr`` of Country objects returned from a
CountryField via a new ``countries_str_attr`` keyword argument (thanks C.
Quentin).
- Add ``pyuca`` as an extra dependency, so that it can be installed like
``pip install django-countries[pyuca]``.
- Add Django 3.2 support.
7.0 (5 December 2020)
=====================
- Add ``name_only`` as 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 in
``COUNTRIES_OVERRIDE`` using 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 django ``Country`` object.
6.0 (28 February 2020)
======================
- Make DRF CountryField respect ``blank=False``. This is a backwards incompatible change since blank input will now
return a validation error (unless ``blank`` is explicitly set to ``True``).
- Fix ``COUNTRIES_OVERRIDE`` when 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 the ``Country`` object.
5.4 (11 August 2019)
====================
- Renamed Macedonia -> North Macedonia.
- Fix an outlying ``makemigrations`` error.
- Pulled in new translations which were provided but missing from previous
version.
- Fixed Simplified Chinese translation (needed to be ``locale/zh_Hans``).
- Introduce an optional complex format for ``COUNTRIES_ONLY`` and
``COUNTRIES_OVERRIDE`` to 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)
====================
- Fix ``dumpdata`` and ``loaddata`` for ``CountryField(multiple=True)``.
5.3 (20 April 2018)
===================
- Iterating a ``Countries`` object 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 for ``CountrySelectWidget``.
- 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 allow ``multiple=True`` and ``null=True`` together. This causes
problems saving the field, and ``null`` shouldn't really be used anyway
because the country field is a subclass of ``CharField``.
4.6 (16 June 2017)
==================
* Add a ``CountryFieldMixin`` Django Rest Framework serializer mixin that
automatically picks the right field type for a ``CountryField`` (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-choice ``CountryField.max_length`` is 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-choice ``CountryField``.
* Tests now cover multiple Django Rest Framework versions (back to 3.3).
4.6.1
-----
* Fix invalid reStructuredText in CHANGES.
4.6.2
-----
* Use transparency layer for flag sprites.
4.5 (18 April 2017)
===================
* Change rest framework field to be based on ``ChoiceField``.
* 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.11
4.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-lazy ``ugettext`` in
the django-countries custom admin filter.
* Back to 100% test coverage.
4.2 (10 March 2017)
===================
* Add sprite flag files (and ``Country.flag_css`` property) to help minimize
HTTP requests.
4.1 (22 February 2017)
======================
* Better default Django admin filter when filtering a country field in a
``ModelAdmin``.
* Fix settings to support Django 1.11
* Fix when using a model instance with a deferred country field.
* Allow ``CountryField`` to 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 code
* Fix tests, 100% coverage
* IOS / OSX unicode flags function
* Fix widget choices on Django 1.9+
* Add ``COUNTRIES_FIRST_SORT``. Thanks Edraak!
4.0.1
-----
* Fix tests for ``COUNTRIES_FIRST_SORT`` (feature still worked, tests didn't).
3.4 (22 October 2015)
=====================
* Extend test suite to cover Django 1.8
* Fix XSS escaping issue in CountrySelectWidget
* Common name changes: fix typo of Moldova, add United Kingdom
* Add ``{% get_country %}`` template tag.
* New ``CountryField`` Django Rest Framework serializer field.
3.4.1
-----
* Fix minor packaging error.
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.
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.
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.
3.1.1 (15 Jan 2015)
-------------------
* Packaging fix (``CHANGES.rst`` wasn't in the manifest)
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*)
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.
3.0.2 (29 Dec 2014)
-------------------
* Fix ``CountrySelectWidget`` failing 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.
* Changed ``COUNTRIES_FLAG_STATIC`` setting to ``COUNTRIES_FLAG_URL``.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1712005260.0
django-countries-7.6.1/LICENSE 0000644 0001750 0001751 00000002060 14602620214 015043 0 ustar 00chris chris Copyright (c) 2010 Chris Beaven and contributors
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE. ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1712005260.0
django-countries-7.6.1/MANIFEST.in 0000644 0001750 0001751 00000000317 14602620214 015577 0 ustar 00chris chris include *.rst
include LICENSE
include django_countries/py.typed
graft django_countries/static/flags
graft django_countries/locale
exclude tox.ini
exclude .isort.cfg
exclude .pre-commit-config.yaml
prune .tx
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1712005260.7406936
django-countries-7.6.1/PKG-INFO 0000644 0001750 0001751 00000074135 14602620215 015150 0 ustar 00chris chris Metadata-Version: 2.1
Name: django-countries
Version: 7.6.1
Summary: Provides a country field for Django models.
Home-page: https://github.com/SmileyChris/django-countries/
Author: Chris Beaven
Author-email: smileychris@gmail.com
License: MIT
Project-URL: Change Log, https://github.com/SmileyChris/django-countries/blob/main/CHANGES.rst
Project-URL: Source Code, https://github.com/SmileyChris/django-countries
Keywords: django,countries,flags
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Framework :: Django
Classifier: Framework :: Django :: 3.2
Classifier: Framework :: Django :: 4.0
Classifier: Framework :: Django :: 4.1
Classifier: Framework :: Django :: 4.2
Classifier: Framework :: Django :: 5.0
Provides-Extra: maintainer
Provides-Extra: dev
Provides-Extra: test
Provides-Extra: pyuca
License-File: LICENSE
================
Django Countries
================
.. image:: https://badge.fury.io/py/django-countries.svg
:alt: PyPI version
:target: https://badge.fury.io/py/django-countries
.. image:: https://github.com/SmileyChris/django-countries/actions/workflows/tests.yml/badge.svg
:alt: Build status
:target: https://github.com/SmileyChris/django-countries/actions/workflows/tests.yml
A 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 standard ``gettext``. If you would
like to help by adding a translation, please visit
https://www.transifex.com/smileychris/django-countries/
.. contents::
:local:
:backlinks: none
Installation
============
1. ``pip install django-countries``
For more accurate sorting of translated country names, install it with the
optional pyuca_ package:
``pip install django-countries[pyuca]``
2. Add ``django_countries`` to ``INSTALLED_APPS``
.. _pyuca: https://pypi.python.org/pypi/pyuca/
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``:
.. code:: python
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:
.. code:: python
>>> 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:
.. code:: python
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 lookups ``contains``, ``startswith``, ``endswith``, ``regex``, or
their case insensitive versions. Use ``__name`` or ``__iname`` for the
``exact``/``iexact`` equivalent:
.. code:: python
>>> Person.objects.filter(country__name="New Zealand").count()
1
>>> Person.objects.filter(country__icontains="zealand").count()
1
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:
.. code:: python
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
By default, countries are stored sorted for data consistency, and any
duplicates are removed. These behaviours can be overridden by using the field
arguments ``multiple_sort=False`` and ``multiple_unique=False`` respectively.
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:
.. code:: jinja
For multiple flag resolutions, use ``sprite-hq.css`` instead and add the
``flag2x``, ``flag3x``, or ``flag4x`` class. For example:
.. code:: jinja
Normal:
Bigger:
You might also want to consider using ``aria-label`` for better
accessibility:
.. code:: jinja
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:
.. code:: python
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:
.. code:: python
'{widget}'
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:
.. code:: python
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:
.. code:: python
>>> 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)
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:
.. code:: jinja
{% load countries %}
{% get_country 'BR' as country %}
{{ country.name }}
If you need a list of countries, there's also a simple tag for that:
.. code:: jinja
{% load countries %}
{% get_countries as countries %}
Customization
=============
Customize the country list
--------------------------
Country 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 the
``COUNTRIES_COMMON_NAMES`` setting to ``False``.
If your project requires the use of alternative names, the inclusion or
exclusion of specific countries then set the ``COUNTRIES_OVERRIDE`` setting to
a dictionary of names which 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:
.. code:: python
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``:
.. code:: python
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):
.. code:: python
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:
.. code:: python
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``:
.. code:: python
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:
.. code:: python
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.
.. _Country: `The Country object`_
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).
.. code:: python
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:
.. code:: python
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:
.. code:: python
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.
.. _Countries: `Single field customization`_
REST output format
^^^^^^^^^^^^^^^^^^
By default, the field will output just the country code. To output the full
country name instead, instantiate 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:: json
{"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:
.. code:: text
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"
}
]
}
}
.. _metadata support: http://www.django-rest-framework.org/api-guide/metadata/
GraphQL
=======
A ``Country`` graphene object type is included that can be used when generating
your schema.
.. code:: python
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
==========
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.
7.6.1 (2 April 2024)
====================
- Fix a TypeError when no country is selected, introduced in the Django 5 fix.
7.6 (27 March 2024)
===================
- Replace deprecated ``pkg_resources.iter_entry_points`` with
``importlib_metadata``.
- Support Django 5.0.
7.5.1 (1 February 2023)
=======================
- Make ``CountryField`` queryset filters also work with country codes in
addition to names.
- Switch to ``pyproject.toml`` rather than ``setup.py`` to 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 the ``CountryField``.
- 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 using ``USE_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 be ``locale/zh_Hant``).
- Update flag of Honduras.
- Add Django 4.0 and 4.1 to the test matrix, dropping 3.0 and 3.1
- Add 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="New Zealand")`` will no longer match
now, but instead new ``__name`` and ``__iname`` filters 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 with ``django-migrations-ignore-attrs`` library.
7.1 (17 March 2021)
===================
- Allow customising the ``str_attr`` of Country objects returned from a
CountryField via a new ``countries_str_attr`` keyword argument (thanks C.
Quentin).
- Add ``pyuca`` as an extra dependency, so that it can be installed like
``pip install django-countries[pyuca]``.
- Add Django 3.2 support.
7.0 (5 December 2020)
=====================
- Add ``name_only`` as 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 in
``COUNTRIES_OVERRIDE`` using 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 django ``Country`` object.
6.0 (28 February 2020)
======================
- Make DRF CountryField respect ``blank=False``. This is a backwards incompatible change since blank input will now
return a validation error (unless ``blank`` is explicitly set to ``True``).
- Fix ``COUNTRIES_OVERRIDE`` when 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 the ``Country`` object.
5.4 (11 August 2019)
====================
- Renamed Macedonia -> North Macedonia.
- Fix an outlying ``makemigrations`` error.
- Pulled in new translations which were provided but missing from previous
version.
- Fixed Simplified Chinese translation (needed to be ``locale/zh_Hans``).
- Introduce an optional complex format for ``COUNTRIES_ONLY`` and
``COUNTRIES_OVERRIDE`` to 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)
====================
- Fix ``dumpdata`` and ``loaddata`` for ``CountryField(multiple=True)``.
5.3 (20 April 2018)
===================
- Iterating a ``Countries`` object 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 for ``CountrySelectWidget``.
- 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 allow ``multiple=True`` and ``null=True`` together. This causes
problems saving the field, and ``null`` shouldn't really be used anyway
because the country field is a subclass of ``CharField``.
4.6 (16 June 2017)
==================
* Add a ``CountryFieldMixin`` Django Rest Framework serializer mixin that
automatically picks the right field type for a ``CountryField`` (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-choice ``CountryField.max_length`` is 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-choice ``CountryField``.
* Tests now cover multiple Django Rest Framework versions (back to 3.3).
4.6.1
-----
* Fix invalid reStructuredText in CHANGES.
4.6.2
-----
* Use transparency layer for flag sprites.
4.5 (18 April 2017)
===================
* Change rest framework field to be based on ``ChoiceField``.
* 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.11
4.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-lazy ``ugettext`` in
the django-countries custom admin filter.
* Back to 100% test coverage.
4.2 (10 March 2017)
===================
* Add sprite flag files (and ``Country.flag_css`` property) to help minimize
HTTP requests.
4.1 (22 February 2017)
======================
* Better default Django admin filter when filtering a country field in a
``ModelAdmin``.
* Fix settings to support Django 1.11
* Fix when using a model instance with a deferred country field.
* Allow ``CountryField`` to 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 code
* Fix tests, 100% coverage
* IOS / OSX unicode flags function
* Fix widget choices on Django 1.9+
* Add ``COUNTRIES_FIRST_SORT``. Thanks Edraak!
4.0.1
-----
* Fix tests for ``COUNTRIES_FIRST_SORT`` (feature still worked, tests didn't).
3.4 (22 October 2015)
=====================
* Extend test suite to cover Django 1.8
* Fix XSS escaping issue in CountrySelectWidget
* Common name changes: fix typo of Moldova, add United Kingdom
* Add ``{% get_country %}`` template tag.
* New ``CountryField`` Django Rest Framework serializer field.
3.4.1
-----
* Fix minor packaging error.
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.
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.
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.
3.1.1 (15 Jan 2015)
-------------------
* Packaging fix (``CHANGES.rst`` wasn't in the manifest)
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*)
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.
3.0.2 (29 Dec 2014)
-------------------
* Fix ``CountrySelectWidget`` failing 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.
* Changed ``COUNTRIES_FLAG_STATIC`` setting to ``COUNTRIES_FLAG_URL``.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1712005260.0
django-countries-7.6.1/README.rst 0000644 0001750 0001751 00000040360 14602620214 015532 0 ustar 00chris chris ================
Django Countries
================
.. image:: https://badge.fury.io/py/django-countries.svg
:alt: PyPI version
:target: https://badge.fury.io/py/django-countries
.. image:: https://github.com/SmileyChris/django-countries/actions/workflows/tests.yml/badge.svg
:alt: Build status
:target: https://github.com/SmileyChris/django-countries/actions/workflows/tests.yml
A 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 standard ``gettext``. If you would
like to help by adding a translation, please visit
https://www.transifex.com/smileychris/django-countries/
.. contents::
:local:
:backlinks: none
Installation
============
1. ``pip install django-countries``
For more accurate sorting of translated country names, install it with the
optional pyuca_ package:
``pip install django-countries[pyuca]``
2. Add ``django_countries`` to ``INSTALLED_APPS``
.. _pyuca: https://pypi.python.org/pypi/pyuca/
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``:
.. code:: python
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:
.. code:: python
>>> 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:
.. code:: python
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 lookups ``contains``, ``startswith``, ``endswith``, ``regex``, or
their case insensitive versions. Use ``__name`` or ``__iname`` for the
``exact``/``iexact`` equivalent:
.. code:: python
>>> Person.objects.filter(country__name="New Zealand").count()
1
>>> Person.objects.filter(country__icontains="zealand").count()
1
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:
.. code:: python
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
By default, countries are stored sorted for data consistency, and any
duplicates are removed. These behaviours can be overridden by using the field
arguments ``multiple_sort=False`` and ``multiple_unique=False`` respectively.
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:
.. code:: jinja
For multiple flag resolutions, use ``sprite-hq.css`` instead and add the
``flag2x``, ``flag3x``, or ``flag4x`` class. For example:
.. code:: jinja
Normal:
Bigger:
You might also want to consider using ``aria-label`` for better
accessibility:
.. code:: jinja
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:
.. code:: python
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:
.. code:: python
'{widget}'
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:
.. code:: python
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:
.. code:: python
>>> 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)
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:
.. code:: jinja
{% load countries %}
{% get_country 'BR' as country %}
{{ country.name }}
If you need a list of countries, there's also a simple tag for that:
.. code:: jinja
{% load countries %}
{% get_countries as countries %}
Customization
=============
Customize the country list
--------------------------
Country 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 the
``COUNTRIES_COMMON_NAMES`` setting to ``False``.
If your project requires the use of alternative names, the inclusion or
exclusion of specific countries then set the ``COUNTRIES_OVERRIDE`` setting to
a dictionary of names which 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:
.. code:: python
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``:
.. code:: python
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):
.. code:: python
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:
.. code:: python
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``:
.. code:: python
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:
.. code:: python
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.
.. _Country: `The Country object`_
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).
.. code:: python
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:
.. code:: python
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:
.. code:: python
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.
.. _Countries: `Single field customization`_
REST output format
^^^^^^^^^^^^^^^^^^
By default, the field will output just the country code. To output the full
country name instead, instantiate 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:: json
{"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:
.. code:: text
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"
}
]
}
}
.. _metadata support: http://www.django-rest-framework.org/api-guide/metadata/
GraphQL
=======
A ``Country`` graphene object type is included that can be used when generating
your schema.
.. code:: python
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
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1712005260.714027
django-countries-7.6.1/django_countries/ 0000755 0001750 0001751 00000000000 14602620215 017376 5 ustar 00chris chris ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1712005260.0
django-countries-7.6.1/django_countries/__init__.py 0000644 0001750 0001751 00000047113 14602620214 021514 0 ustar 00chris chris #!/usr/bin/env python
import itertools
import re
from contextlib import contextmanager
from gettext import NullTranslations
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
NamedTuple,
Optional,
Set,
Tuple,
Union,
cast,
overload,
)
from asgiref.local import Local
from django.utils.encoding import force_str
from django.utils.translation import override, trans_real
from typing_extensions import Literal, TypedDict
from django_countries.conf import settings
from .base import CountriesBase
if TYPE_CHECKING:
from django_stubs_ext import StrPromise
try:
import pyuca # type: ignore
collator = pyuca.Collator()
# Use UCA sorting if it's available.
def sort_key(item: Tuple[str, str]) -> Any:
return collator.sort_key(item[1])
except ImportError:
# Fallback if the UCA sorting is not available.
import unicodedata
# Cheap and dirty method to sort against ASCII characters only.
def sort_key(item: Tuple[str, str]) -> Any:
return (
unicodedata.normalize("NFKD", item[1])
.encode("ascii", "ignore")
.decode("ascii")
)
_translation_state = Local()
class EmptyFallbackTranslator(NullTranslations):
def gettext(self, message: str) -> str:
if not getattr(_translation_state, "fallback", True):
# Interrupt the fallback chain.
return ""
return super().gettext(message)
@contextmanager
def no_translation_fallback():
if not settings.USE_I18N:
yield
return
# Ensure the empty fallback translator has been installed.
catalog = trans_real.catalog()
original_fallback = catalog._fallback
if not isinstance(original_fallback, EmptyFallbackTranslator):
empty_fallback_translator = EmptyFallbackTranslator()
empty_fallback_translator._fallback = original_fallback
catalog._fallback = empty_fallback_translator
# Set the translation state to not use a fallback while inside this context.
_translation_state.fallback = False
try:
yield
finally:
_translation_state.fallback = True
class ComplexCountryName(TypedDict):
name: "StrPromise"
names: "List[StrPromise]"
alpha3: str
numeric: int
ioc_code: str
CountryName = Union["StrPromise", ComplexCountryName]
CountryCode = Union[str, int, None]
class AltCodes(NamedTuple):
alpha3: str
numeric: Optional[int]
class CountryTuple(NamedTuple):
code: str
name: str
def __repr__(self) -> str:
"""
Display the repr as a standard tuple for better backwards
compatibility with outputting this in a template.
"""
return f"({self.code!r}, {self.name!r})"
class Countries(CountriesBase):
"""
An object containing a list of ISO3166-1 countries.
Iterating this object will return the countries as namedtuples (of
the country ``code`` and ``name``), sorted by name.
"""
_countries: Dict[str, CountryName]
_alt_codes: Dict[str, AltCodes]
def get_option(self, option: str):
"""
Get a configuration option, trying the options attribute first and
falling back to a Django project setting.
"""
value = getattr(self, option, None)
if value is not None:
return value
return getattr(settings, f"COUNTRIES_{option.upper()}")
@property
def countries(self) -> Dict[str, CountryName]:
"""
Return the a dictionary of countries, modified by any overriding
options.
The result is cached so future lookups are less work intensive.
"""
if not hasattr(self, "_countries"):
only: "Iterable[Union[str, Tuple[str, StrPromise]]]" = self.get_option(
"only"
)
only_choices = True
if only:
# Originally used ``only`` as a dict, still supported.
if not isinstance(only, dict):
for item in only:
if isinstance(item, str):
only_choices = False
break
self._shadowed_names: "Dict[str, List[StrPromise]]" = {}
if only and only_choices:
self._countries = dict(only) # type: ignore
else:
# Local import so that countries aren't loaded into memory
# until first used.
from django_countries.data import COUNTRIES
countries_dict = dict(COUNTRIES)
if only:
self._countries = {}
for item in only:
if isinstance(item, str):
self._countries[item] = countries_dict[item]
else:
key, value = item
self._countries[key] = value
else:
self._countries = countries_dict.copy() # type: ignore
if self.get_option("common_names"):
for code, name in self.COMMON_NAMES.items():
if code in self._countries:
self._countries[code] = name
override: Dict[str, Union[CountryName, None]] = self.get_option(
"override"
)
if override:
_countries = cast(
Dict[str, Union[CountryName, None]], self._countries.copy()
)
_countries.update(override)
self._countries = {
code: name
for code, name in _countries.items()
if name is not None
}
if self.get_option("common_names"):
for code in self.COMMON_NAMES:
if code in self._countries and code not in override:
self._shadowed_names[code] = [countries_dict[code]]
for code, names in self.OLD_NAMES.items():
if code in self._countries and code not in override:
country_shadowed = self._shadowed_names.setdefault(code, [])
country_shadowed.extend(names)
self.countries_first = []
first: List[str] = self.get_option("first") or []
for code in first:
code = self.alpha2(code)
if code in self._countries:
self.countries_first.append(code)
return self._countries
@countries.deleter
def countries(self):
"""
Reset the countries cache in case for some crazy reason the settings or
internal options change. But surely no one is crazy enough to do that,
right?
"""
if hasattr(self, "_countries"):
del self._countries
if hasattr(self, "_alt_codes"):
del self._alt_codes
if hasattr(self, "_ioc_codes"):
del self._ioc_codes
if hasattr(self, "_shadowed_names"):
del self._shadowed_names
@property
def alt_codes(self) -> Dict[str, AltCodes]:
if not hasattr(self, "_alt_codes"):
# Again, local import so data is not loaded unless it's needed.
from django_countries.data import ALT_CODES
self._alt_codes = ALT_CODES # type: ignore
altered = False
for code, country in self.countries.items():
if isinstance(country, dict) and (
"alpha3" in country or "numeric" in country
):
if not altered:
self._alt_codes = self._alt_codes.copy()
altered = True
alpha3, numeric = self._alt_codes.get(code, ("", None))
if "alpha3" in country:
alpha3 = country["alpha3"]
if "numeric" in country:
numeric = country["numeric"]
self._alt_codes[code] = AltCodes(alpha3, numeric)
return self._alt_codes
@property
def ioc_codes(self) -> Dict[str, str]:
if not hasattr(self, "_ioc_codes"):
from django_countries.ioc_data import ISO_TO_IOC
self._ioc_codes = ISO_TO_IOC
altered = False
for code, country in self.countries.items():
if isinstance(country, dict) and "ioc_code" in country:
if not altered:
self._ioc_codes = self._ioc_codes.copy()
altered = True
self._ioc_codes[code] = country["ioc_code"]
return self._ioc_codes
@property
def shadowed_names(self):
if not getattr(self, "_shadowed_names", False):
# Getting countries populates shadowed names.
self.countries
return self._shadowed_names
def translate_code(self, code: str, ignore_first: Optional[List[str]] = None):
"""
Return translated countries for a country code.
"""
country = self.countries[code]
if isinstance(country, dict):
if "names" in country:
names = country["names"]
else:
names = [country["name"]]
else:
names = [country]
if ignore_first and code in ignore_first:
names = names[1:]
for name in names:
yield self.translate_pair(code, name)
def translate_pair(self, code: str, name: Optional[CountryName] = None):
"""
Force a country to the current activated translation.
:returns: ``CountryTuple(code, translated_country_name)`` namedtuple
"""
if name is None:
name = self.countries[code]
if isinstance(name, dict):
if "names" in name:
fallback_names: "List[StrPromise]" = name["names"][1:]
name = name["names"][0]
else:
fallback_names = []
name = name["name"]
else:
fallback_names = self.shadowed_names.get(code, [])
if fallback_names:
with no_translation_fallback():
country_name = force_str(name)
# Check if there's an older translation available if there's no
# translation for the newest name.
if not country_name:
for fallback_name in fallback_names:
fallback_name_str = force_str(fallback_name)
if fallback_name_str:
country_name = fallback_name_str
break
if not country_name:
# Use the translation's fallback country name.
country_name = force_str(name)
else:
country_name = force_str(name)
return CountryTuple(code, country_name)
def __iter__(self):
"""
Iterate through countries, sorted by name.
Each country record consists of a namedtuple of the two letter
ISO3166-1 country ``code`` and short ``name``.
The sorting happens based on the thread's current translation.
Countries that are in ``settings.COUNTRIES_FIRST`` will be
displayed before any sorted countries (in the order provided),
and are only repeated in the sorted list if
``settings.COUNTRIES_FIRST_REPEAT`` is ``True``.
The first countries can be separated from the sorted list by the
value provided in ``settings.COUNTRIES_FIRST_BREAK``.
"""
# Initializes countries_first, so needs to happen first.
countries = self.countries
# Yield countries that should be displayed first.
countries_first = (self.translate_pair(code) for code in self.countries_first)
if self.get_option("first_sort"):
countries_first = sorted(countries_first, key=sort_key)
yield from countries_first
if self.countries_first:
first_break = self.get_option("first_break")
if first_break:
yield CountryTuple("", force_str(first_break))
# Force translation before sorting.
ignore_first = None if self.get_option("first_repeat") else self.countries_first
countries = tuple(
itertools.chain.from_iterable(
self.translate_code(code, ignore_first) for code in countries
)
)
# Return sorted country list.
yield from sorted(countries, key=sort_key)
def alpha2(self, code: CountryCode) -> str:
"""
Return the normalized country code when passed any type of ISO 3166-1
country code.
Overridden countries objects may actually have country codes that are
not two characters (for example, "GB-WLS"), so the returned length of
the code is not guaranteed.
If no match is found, returns an empty string.
"""
find: Optional[Callable]
code_str = force_str(code).upper()
if code_str.isdigit():
lookup_numeric = int(code_str)
def find(alt_codes):
return alt_codes[1] == lookup_numeric
elif len(code_str) == 3:
lookup_alpha3 = code_str
def find(alt_codes) -> bool:
return alt_codes[0] == lookup_alpha3
else:
find = None
if find:
code_str = ""
for alpha2, alt_codes in self.alt_codes.items():
if find(alt_codes):
code_str = alpha2
break
if code_str in self.countries:
return code_str
return ""
def name(self, code: CountryCode) -> str:
"""
Return the name of a country, based on the code.
If no match is found, returns an empty string.
"""
alpha2 = self.alpha2(code)
if alpha2 not in self.countries:
return ""
return self.translate_pair(alpha2)[1]
@overload
def by_name(
self,
country: str,
*,
regex: Literal[False] = False,
language: str = "en",
insensitive: bool = True,
) -> str:
...
@overload
def by_name(
self,
country: str,
*,
regex: Literal[True],
language: str = "en",
insensitive: bool = True,
) -> Set[str]:
...
def by_name(
self,
country: str,
*,
regex: bool = False,
language: str = "en",
insensitive: bool = True,
) -> Union[str, Set[str]]:
"""
Fetch a country's ISO3166-1 two letter country code from its name.
An optional language parameter is also available. Warning: This depends
on the quality of the available translations.
If no match is found, returns an empty string.
If ``regex`` is set to True, then rather than returning a string
containing the matching country code or an empty string, a set of
matching country codes is returned.
If ``insensitive`` is set to False (True by default), then the search
will be case sensitive.
..warning:: Be cautious about relying on this returning a country code
(especially with any hard-coded string) since the ISO names of
countries may change over time.
"""
code_list = set()
if regex:
re_match = re.compile(country, insensitive and re.IGNORECASE)
elif insensitive:
country = country.lower()
with override(language):
for code, check_country in self.countries.items():
if isinstance(check_country, dict):
if "names" in check_country:
check_names: "List[StrPromise]" = check_country["names"]
else:
check_names = [check_country["name"]]
else:
check_names = [check_country]
for name in check_names:
if regex:
if re_match.search(str(name)):
code_list.add(code)
else:
if insensitive:
if country == name.lower():
return code
else:
if country == name:
return code
if code in self.shadowed_names:
for shadowed_name in self.shadowed_names[code]:
if regex:
if re_match.search(str(shadowed_name)):
code_list.add(code)
else:
if insensitive:
shadowed_name = shadowed_name.lower()
if country == shadowed_name:
return code
if regex:
return code_list
return ""
def alpha3(self, code: CountryCode) -> str:
"""
Return the ISO 3166-1 three letter country code matching the provided
country code.
If no match is found, returns an empty string.
"""
alpha2 = self.alpha2(code)
try:
alpha3 = self.alt_codes[alpha2][0]
except KeyError:
alpha3 = ""
return alpha3 or ""
@overload
def numeric(
self, code: Union[str, int, None], padded: Literal[False] = False
) -> Optional[int]:
...
@overload
def numeric(
self, code: Union[str, int, None], padded: Literal[True]
) -> Optional[str]:
...
def numeric(self, code: Union[str, int, None], padded: bool = False):
"""
Return the ISO 3166-1 numeric country code matching the provided
country code.
If no match is found, returns ``None``.
:param padded: Pass ``True`` to return a 0-padded three character
string, otherwise an integer will be returned.
"""
alpha2 = self.alpha2(code)
try:
num = self.alt_codes[alpha2][1]
except KeyError:
num = None
if num is None:
return None
if padded:
return "%03d" % num
return num
def ioc_code(self, code: CountryCode) -> str:
"""
Return the International Olympic Committee three letter code matching
the provided ISO 3166-1 country code.
If no match is found, returns an empty string.
"""
alpha2 = self.alpha2(code)
return self.ioc_codes.get(alpha2, "")
def __len__(self):
"""
len() used by several third party applications to calculate the length
of choices. This will solve a bug related to generating fixtures.
"""
count = len(self.countries)
# Add first countries, and the break if necessary.
count += len(self.countries_first)
if self.countries_first and self.get_option("first_break"):
count += 1
return count
def __bool__(self):
return bool(self.countries)
def __contains__(self, code):
"""
Check to see if the countries contains the given code.
"""
return code in self.countries
def __getitem__(self, index):
"""
Some applications expect to be able to access members of the field
choices by index.
"""
try:
return next(itertools.islice(self.__iter__(), index, index + 1))
except TypeError:
return list(
itertools.islice(self.__iter__(), index.start, index.stop, index.step)
)
countries = Countries()
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1712005260.0
django-countries-7.6.1/django_countries/base.py 0000644 0001750 0001751 00000002244 14602620214 020663 0 ustar 00chris chris from typing import TYPE_CHECKING
if TYPE_CHECKING:
from django_stubs_ext import StrPromise
try:
from django.utils.translation import gettext_lazy as _
except ImportError: # pragma: no cover
# Allows this module to be executed without Django installed.
def _(message: str) -> "StrPromise":
return message # type: ignore
class CountriesBase:
COMMON_NAMES = {
"BN": _("Brunei"),
"BO": _("Bolivia"),
"FM": _("Micronesia"),
"GB": _("United Kingdom"),
"IR": _("Iran"),
"KP": _("North Korea"),
"KR": _("South Korea"),
"LA": _("Laos"),
"MD": _("Moldova"),
"RU": _("Russia"),
"SY": _("Syria"),
"TW": _("Taiwan"),
"TZ": _("Tanzania"),
"VE": _("Venezuela"),
"VN": _("Vietnam"),
}
OLD_NAMES = {
"CZ": [_("Czech Republic")],
"MK": [_("Macedonia"), _("Macedonia (the former Yugoslav Republic of)")],
"SZ": [_("Swaziland")],
"TZ": [_("Tanzania, the United Republic of")],
"FK": [_("Falkland Islands [Malvinas]")],
"TR": [_("Turkey")],
}
def __getstate__(self):
return None
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1712005260.0
django-countries-7.6.1/django_countries/conf.py 0000644 0001750 0001751 00000005417 14602620214 020703 0 ustar 00chris chris from typing import Any, Dict, List
import django.conf
class AppSettings:
"""
A holder for app-specific default settings that allows overriding via
the project's settings.
"""
def __getattribute__(self, attr: str):
if attr == attr.upper():
try:
return getattr(django.conf.settings, attr)
except AttributeError:
pass
return super().__getattribute__(attr)
class Settings(AppSettings):
COUNTRIES_FLAG_URL = "flags/{code}.gif"
"""
The URL for a flag.
It can either be relative to the static url, 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'``
"""
COUNTRIES_COMMON_NAMES = True
"""
Whether to use the common names for some countries, as opposed to the
official ISO name.
Some examples:
"Bolivia" instead of "Bolivia, Plurinational State of"
"South Korea" instead of "Korea (the Republic of)"
"Taiwan" instead of "Taiwan (Province of China)"
"""
COUNTRIES_OVERRIDE: Dict[str, Any] = {}
"""
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
}
"""
COUNTRIES_ONLY: Dict[str, Any] = {}
"""
Similar to COUNTRIES_OVERRIDE
A dictionary of names to include in selection.
Note that you will need to handle translation of customised country names.
For example::
COUNTRIES_ONLY = {
'NZ': _('Middle Earth'),
'AU': _('Desert'),
}
"""
COUNTRIES_FIRST: List[str] = []
"""
Countries matching the country codes provided in this list will be shown
first in the countries list (in the order specified) before all the
alphanumerically sorted countries.
"""
COUNTRIES_FIRST_REPEAT = False
"""
Countries listed in :attr:`COUNTRIES_FIRST` will be repeated again in the
alphanumerically sorted list if set to ``True``.
"""
COUNTRIES_FIRST_BREAK = None
"""
Countries listed in :attr:`COUNTRIES_FIRST` will be followed by a null
choice with this title (if set) before all the alphanumerically sorted
countries.
"""
COUNTRIES_FIRST_SORT = False
"""
Countries listed in :attr:`COUNTRIES_FIRST` will be alphanumerically
sorted based on their translated name instead of relying on their
order in :attr:`COUNTRIES_FIRST`.
"""
settings = Settings()
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1712005260.0
django-countries-7.6.1/django_countries/data.py 0000755 0001750 0001751 00000042513 14602620214 020670 0 ustar 00chris chris #!/usr/bin/env python
"""
This is a self-generating script that contains all of the iso3166-1 data.
To regenerate, a CSV file must be created that contains the latest data. Here's
how to do that:
1. Visit https://www.iso.org/obp
2. Click the "Country Codes" radio option and click the search button
3. Change the results per page to 300
4. Copy the html table and paste into Libreoffice Calc / Excel
5. Delete the French short name column
6. Delete the heading row.
7. Save as a CSV file in django_countries/iso3166-1.csv
8. Run this script from the command line
"""
import glob
import os
from typing import TYPE_CHECKING, Dict
from django_countries.base import CountriesBase
if TYPE_CHECKING:
from django_stubs_ext import StrPromise
try:
from django.utils.translation import gettext_lazy as _
except ImportError: # pragma: no cover
# Allows this module to be executed without Django installed.
def _(message: str) -> "StrPromise":
return message # type: ignore
# Nicely titled (and translatable) country names.
COUNTRIES: "Dict[str, StrPromise]" = {
"AF": _("Afghanistan"),
"AX": _("Åland Islands"),
"AL": _("Albania"),
"DZ": _("Algeria"),
"AS": _("American Samoa"),
"AD": _("Andorra"),
"AO": _("Angola"),
"AI": _("Anguilla"),
"AQ": _("Antarctica"),
"AG": _("Antigua and Barbuda"),
"AR": _("Argentina"),
"AM": _("Armenia"),
"AW": _("Aruba"),
"AU": _("Australia"),
"AT": _("Austria"),
"AZ": _("Azerbaijan"),
"BS": _("Bahamas"),
"BH": _("Bahrain"),
"BD": _("Bangladesh"),
"BB": _("Barbados"),
"BY": _("Belarus"),
"BE": _("Belgium"),
"BZ": _("Belize"),
"BJ": _("Benin"),
"BM": _("Bermuda"),
"BT": _("Bhutan"),
"BO": _("Bolivia (Plurinational State of)"),
"BQ": _("Bonaire, Sint Eustatius and Saba"),
"BA": _("Bosnia and Herzegovina"),
"BW": _("Botswana"),
"BV": _("Bouvet Island"),
"BR": _("Brazil"),
"IO": _("British Indian Ocean Territory"),
"BN": _("Brunei Darussalam"),
"BG": _("Bulgaria"),
"BF": _("Burkina Faso"),
"BI": _("Burundi"),
"CV": _("Cabo Verde"),
"KH": _("Cambodia"),
"CM": _("Cameroon"),
"CA": _("Canada"),
"KY": _("Cayman Islands"),
"CF": _("Central African Republic"),
"TD": _("Chad"),
"CL": _("Chile"),
"CN": _("China"),
"CX": _("Christmas Island"),
"CC": _("Cocos (Keeling) Islands"),
"CO": _("Colombia"),
"KM": _("Comoros"),
"CG": _("Congo"),
"CD": _("Congo (the Democratic Republic of the)"),
"CK": _("Cook Islands"),
"CR": _("Costa Rica"),
"CI": _("Côte d'Ivoire"),
"HR": _("Croatia"),
"CU": _("Cuba"),
"CW": _("Curaçao"),
"CY": _("Cyprus"),
"CZ": _("Czechia"),
"DK": _("Denmark"),
"DJ": _("Djibouti"),
"DM": _("Dominica"),
"DO": _("Dominican Republic"),
"EC": _("Ecuador"),
"EG": _("Egypt"),
"SV": _("El Salvador"),
"GQ": _("Equatorial Guinea"),
"ER": _("Eritrea"),
"EE": _("Estonia"),
"SZ": _("Eswatini"),
"ET": _("Ethiopia"),
"FK": _("Falkland Islands (Malvinas)"),
"FO": _("Faroe Islands"),
"FJ": _("Fiji"),
"FI": _("Finland"),
"FR": _("France"),
"GF": _("French Guiana"),
"PF": _("French Polynesia"),
"TF": _("French Southern Territories"),
"GA": _("Gabon"),
"GM": _("Gambia"),
"GE": _("Georgia"),
"DE": _("Germany"),
"GH": _("Ghana"),
"GI": _("Gibraltar"),
"GR": _("Greece"),
"GL": _("Greenland"),
"GD": _("Grenada"),
"GP": _("Guadeloupe"),
"GU": _("Guam"),
"GT": _("Guatemala"),
"GG": _("Guernsey"),
"GN": _("Guinea"),
"GW": _("Guinea-Bissau"),
"GY": _("Guyana"),
"HT": _("Haiti"),
"HM": _("Heard Island and McDonald Islands"),
"VA": _("Holy See"),
"HN": _("Honduras"),
"HK": _("Hong Kong"),
"HU": _("Hungary"),
"IS": _("Iceland"),
"IN": _("India"),
"ID": _("Indonesia"),
"IR": _("Iran (Islamic Republic of)"),
"IQ": _("Iraq"),
"IE": _("Ireland"),
"IM": _("Isle of Man"),
"IL": _("Israel"),
"IT": _("Italy"),
"JM": _("Jamaica"),
"JP": _("Japan"),
"JE": _("Jersey"),
"JO": _("Jordan"),
"KZ": _("Kazakhstan"),
"KE": _("Kenya"),
"KI": _("Kiribati"),
"KP": _("Korea (the Democratic People's Republic of)"),
"KR": _("Korea (the Republic of)"),
"KW": _("Kuwait"),
"KG": _("Kyrgyzstan"),
"LA": _("Lao People's Democratic Republic"),
"LV": _("Latvia"),
"LB": _("Lebanon"),
"LS": _("Lesotho"),
"LR": _("Liberia"),
"LY": _("Libya"),
"LI": _("Liechtenstein"),
"LT": _("Lithuania"),
"LU": _("Luxembourg"),
"MO": _("Macao"),
"MG": _("Madagascar"),
"MW": _("Malawi"),
"MY": _("Malaysia"),
"MV": _("Maldives"),
"ML": _("Mali"),
"MT": _("Malta"),
"MH": _("Marshall Islands"),
"MQ": _("Martinique"),
"MR": _("Mauritania"),
"MU": _("Mauritius"),
"YT": _("Mayotte"),
"MX": _("Mexico"),
"FM": _("Micronesia (Federated States of)"),
"MD": _("Moldova (the Republic of)"),
"MC": _("Monaco"),
"MN": _("Mongolia"),
"ME": _("Montenegro"),
"MS": _("Montserrat"),
"MA": _("Morocco"),
"MZ": _("Mozambique"),
"MM": _("Myanmar"),
"NA": _("Namibia"),
"NR": _("Nauru"),
"NP": _("Nepal"),
"NL": _("Netherlands"),
"NC": _("New Caledonia"),
"NZ": _("New Zealand"),
"NI": _("Nicaragua"),
"NE": _("Niger"),
"NG": _("Nigeria"),
"NU": _("Niue"),
"NF": _("Norfolk Island"),
"MK": _("North Macedonia"),
"MP": _("Northern Mariana Islands"),
"NO": _("Norway"),
"OM": _("Oman"),
"PK": _("Pakistan"),
"PW": _("Palau"),
"PS": _("Palestine, State of"),
"PA": _("Panama"),
"PG": _("Papua New Guinea"),
"PY": _("Paraguay"),
"PE": _("Peru"),
"PH": _("Philippines"),
"PN": _("Pitcairn"),
"PL": _("Poland"),
"PT": _("Portugal"),
"PR": _("Puerto Rico"),
"QA": _("Qatar"),
"RE": _("Réunion"),
"RO": _("Romania"),
"RU": _("Russian Federation"),
"RW": _("Rwanda"),
"BL": _("Saint Barthélemy"),
"SH": _("Saint Helena, Ascension and Tristan da Cunha"),
"KN": _("Saint Kitts and Nevis"),
"LC": _("Saint Lucia"),
"MF": _("Saint Martin (French part)"),
"PM": _("Saint Pierre and Miquelon"),
"VC": _("Saint Vincent and the Grenadines"),
"WS": _("Samoa"),
"SM": _("San Marino"),
"ST": _("Sao Tome and Principe"),
"SA": _("Saudi Arabia"),
"SN": _("Senegal"),
"RS": _("Serbia"),
"SC": _("Seychelles"),
"SL": _("Sierra Leone"),
"SG": _("Singapore"),
"SX": _("Sint Maarten (Dutch part)"),
"SK": _("Slovakia"),
"SI": _("Slovenia"),
"SB": _("Solomon Islands"),
"SO": _("Somalia"),
"ZA": _("South Africa"),
"GS": _("South Georgia and the South Sandwich Islands"),
"SS": _("South Sudan"),
"ES": _("Spain"),
"LK": _("Sri Lanka"),
"SD": _("Sudan"),
"SR": _("Suriname"),
"SJ": _("Svalbard and Jan Mayen"),
"SE": _("Sweden"),
"CH": _("Switzerland"),
"SY": _("Syrian Arab Republic"),
"TW": _("Taiwan (Province of China)"),
"TJ": _("Tajikistan"),
"TZ": _("Tanzania, the United Republic of"),
"TH": _("Thailand"),
"TL": _("Timor-Leste"),
"TG": _("Togo"),
"TK": _("Tokelau"),
"TO": _("Tonga"),
"TT": _("Trinidad and Tobago"),
"TN": _("Tunisia"),
"TR": _("Türkiye"),
"TM": _("Turkmenistan"),
"TC": _("Turks and Caicos Islands"),
"TV": _("Tuvalu"),
"UG": _("Uganda"),
"UA": _("Ukraine"),
"AE": _("United Arab Emirates"),
"GB": _("United Kingdom of Great Britain and Northern Ireland"),
"UM": _("United States Minor Outlying Islands"),
"US": _("United States of America"),
"UY": _("Uruguay"),
"UZ": _("Uzbekistan"),
"VU": _("Vanuatu"),
"VE": _("Venezuela (Bolivarian Republic of)"),
"VN": _("Viet Nam"),
"VG": _("Virgin Islands (British)"),
"VI": _("Virgin Islands (U.S.)"),
"WF": _("Wallis and Futuna"),
"EH": _("Western Sahara"),
"YE": _("Yemen"),
"ZM": _("Zambia"),
"ZW": _("Zimbabwe"),
}
ALT_CODES = {
"AF": ("AFG", 4),
"AX": ("ALA", 248),
"AL": ("ALB", 8),
"DZ": ("DZA", 12),
"AS": ("ASM", 16),
"AD": ("AND", 20),
"AO": ("AGO", 24),
"AI": ("AIA", 660),
"AQ": ("ATA", 10),
"AG": ("ATG", 28),
"AR": ("ARG", 32),
"AM": ("ARM", 51),
"AW": ("ABW", 533),
"AU": ("AUS", 36),
"AT": ("AUT", 40),
"AZ": ("AZE", 31),
"BS": ("BHS", 44),
"BH": ("BHR", 48),
"BD": ("BGD", 50),
"BB": ("BRB", 52),
"BY": ("BLR", 112),
"BE": ("BEL", 56),
"BZ": ("BLZ", 84),
"BJ": ("BEN", 204),
"BM": ("BMU", 60),
"BT": ("BTN", 64),
"BO": ("BOL", 68),
"BQ": ("BES", 535),
"BA": ("BIH", 70),
"BW": ("BWA", 72),
"BV": ("BVT", 74),
"BR": ("BRA", 76),
"IO": ("IOT", 86),
"BN": ("BRN", 96),
"BG": ("BGR", 100),
"BF": ("BFA", 854),
"BI": ("BDI", 108),
"CV": ("CPV", 132),
"KH": ("KHM", 116),
"CM": ("CMR", 120),
"CA": ("CAN", 124),
"KY": ("CYM", 136),
"CF": ("CAF", 140),
"TD": ("TCD", 148),
"CL": ("CHL", 152),
"CN": ("CHN", 156),
"CX": ("CXR", 162),
"CC": ("CCK", 166),
"CO": ("COL", 170),
"KM": ("COM", 174),
"CG": ("COG", 178),
"CD": ("COD", 180),
"CK": ("COK", 184),
"CR": ("CRI", 188),
"CI": ("CIV", 384),
"HR": ("HRV", 191),
"CU": ("CUB", 192),
"CW": ("CUW", 531),
"CY": ("CYP", 196),
"CZ": ("CZE", 203),
"DK": ("DNK", 208),
"DJ": ("DJI", 262),
"DM": ("DMA", 212),
"DO": ("DOM", 214),
"EC": ("ECU", 218),
"EG": ("EGY", 818),
"SV": ("SLV", 222),
"GQ": ("GNQ", 226),
"ER": ("ERI", 232),
"EE": ("EST", 233),
"SZ": ("SWZ", 748),
"ET": ("ETH", 231),
"FK": ("FLK", 238),
"FO": ("FRO", 234),
"FJ": ("FJI", 242),
"FI": ("FIN", 246),
"FR": ("FRA", 250),
"GF": ("GUF", 254),
"PF": ("PYF", 258),
"TF": ("ATF", 260),
"GA": ("GAB", 266),
"GM": ("GMB", 270),
"GE": ("GEO", 268),
"DE": ("DEU", 276),
"GH": ("GHA", 288),
"GI": ("GIB", 292),
"GR": ("GRC", 300),
"GL": ("GRL", 304),
"GD": ("GRD", 308),
"GP": ("GLP", 312),
"GU": ("GUM", 316),
"GT": ("GTM", 320),
"GG": ("GGY", 831),
"GN": ("GIN", 324),
"GW": ("GNB", 624),
"GY": ("GUY", 328),
"HT": ("HTI", 332),
"HM": ("HMD", 334),
"VA": ("VAT", 336),
"HN": ("HND", 340),
"HK": ("HKG", 344),
"HU": ("HUN", 348),
"IS": ("ISL", 352),
"IN": ("IND", 356),
"ID": ("IDN", 360),
"IR": ("IRN", 364),
"IQ": ("IRQ", 368),
"IE": ("IRL", 372),
"IM": ("IMN", 833),
"IL": ("ISR", 376),
"IT": ("ITA", 380),
"JM": ("JAM", 388),
"JP": ("JPN", 392),
"JE": ("JEY", 832),
"JO": ("JOR", 400),
"KZ": ("KAZ", 398),
"KE": ("KEN", 404),
"KI": ("KIR", 296),
"KP": ("PRK", 408),
"KR": ("KOR", 410),
"KW": ("KWT", 414),
"KG": ("KGZ", 417),
"LA": ("LAO", 418),
"LV": ("LVA", 428),
"LB": ("LBN", 422),
"LS": ("LSO", 426),
"LR": ("LBR", 430),
"LY": ("LBY", 434),
"LI": ("LIE", 438),
"LT": ("LTU", 440),
"LU": ("LUX", 442),
"MO": ("MAC", 446),
"MG": ("MDG", 450),
"MW": ("MWI", 454),
"MY": ("MYS", 458),
"MV": ("MDV", 462),
"ML": ("MLI", 466),
"MT": ("MLT", 470),
"MH": ("MHL", 584),
"MQ": ("MTQ", 474),
"MR": ("MRT", 478),
"MU": ("MUS", 480),
"YT": ("MYT", 175),
"MX": ("MEX", 484),
"FM": ("FSM", 583),
"MD": ("MDA", 498),
"MC": ("MCO", 492),
"MN": ("MNG", 496),
"ME": ("MNE", 499),
"MS": ("MSR", 500),
"MA": ("MAR", 504),
"MZ": ("MOZ", 508),
"MM": ("MMR", 104),
"NA": ("NAM", 516),
"NR": ("NRU", 520),
"NP": ("NPL", 524),
"NL": ("NLD", 528),
"NC": ("NCL", 540),
"NZ": ("NZL", 554),
"NI": ("NIC", 558),
"NE": ("NER", 562),
"NG": ("NGA", 566),
"NU": ("NIU", 570),
"NF": ("NFK", 574),
"MK": ("MKD", 807),
"MP": ("MNP", 580),
"NO": ("NOR", 578),
"OM": ("OMN", 512),
"PK": ("PAK", 586),
"PW": ("PLW", 585),
"PS": ("PSE", 275),
"PA": ("PAN", 591),
"PG": ("PNG", 598),
"PY": ("PRY", 600),
"PE": ("PER", 604),
"PH": ("PHL", 608),
"PN": ("PCN", 612),
"PL": ("POL", 616),
"PT": ("PRT", 620),
"PR": ("PRI", 630),
"QA": ("QAT", 634),
"RE": ("REU", 638),
"RO": ("ROU", 642),
"RU": ("RUS", 643),
"RW": ("RWA", 646),
"BL": ("BLM", 652),
"SH": ("SHN", 654),
"KN": ("KNA", 659),
"LC": ("LCA", 662),
"MF": ("MAF", 663),
"PM": ("SPM", 666),
"VC": ("VCT", 670),
"WS": ("WSM", 882),
"SM": ("SMR", 674),
"ST": ("STP", 678),
"SA": ("SAU", 682),
"SN": ("SEN", 686),
"RS": ("SRB", 688),
"SC": ("SYC", 690),
"SL": ("SLE", 694),
"SG": ("SGP", 702),
"SX": ("SXM", 534),
"SK": ("SVK", 703),
"SI": ("SVN", 705),
"SB": ("SLB", 90),
"SO": ("SOM", 706),
"ZA": ("ZAF", 710),
"GS": ("SGS", 239),
"SS": ("SSD", 728),
"ES": ("ESP", 724),
"LK": ("LKA", 144),
"SD": ("SDN", 729),
"SR": ("SUR", 740),
"SJ": ("SJM", 744),
"SE": ("SWE", 752),
"CH": ("CHE", 756),
"SY": ("SYR", 760),
"TW": ("TWN", 158),
"TJ": ("TJK", 762),
"TZ": ("TZA", 834),
"TH": ("THA", 764),
"TL": ("TLS", 626),
"TG": ("TGO", 768),
"TK": ("TKL", 772),
"TO": ("TON", 776),
"TT": ("TTO", 780),
"TN": ("TUN", 788),
"TR": ("TUR", 792),
"TM": ("TKM", 795),
"TC": ("TCA", 796),
"TV": ("TUV", 798),
"UG": ("UGA", 800),
"UA": ("UKR", 804),
"AE": ("ARE", 784),
"GB": ("GBR", 826),
"UM": ("UMI", 581),
"US": ("USA", 840),
"UY": ("URY", 858),
"UZ": ("UZB", 860),
"VU": ("VUT", 548),
"VE": ("VEN", 862),
"VN": ("VNM", 704),
"VG": ("VGB", 92),
"VI": ("VIR", 850),
"WF": ("WLF", 876),
"EH": ("ESH", 732),
"YE": ("YEM", 887),
"ZM": ("ZMB", 894),
"ZW": ("ZWE", 716),
}
def self_generate(
output_filename: str, filename: str = "iso3166-1.csv"
): # pragma: no cover
"""
The following code can be used for self-generation of this file.
It requires a UTF-8 CSV file containing the short ISO name and two letter
country code as the first two columns.
"""
import csv
import re
import unicodedata
countries = []
with open(filename) as csv_file:
for row in csv.reader(csv_file):
name = row[0].rstrip("*")
name = re.sub(r"\(the\)", "", name)
name = re.sub(r" +\[(.+)\]", r" (\1)", name)
if name:
countries.append((name, row[1], row[2], int(row[3])))
with open(__file__) as source_file:
contents = source_file.read()
# Sort countries.
def sort_key(row):
return (
unicodedata.normalize("NFKD", row[0])
.encode("ascii", "ignore")
.decode("ascii")
)
countries = sorted(countries, key=sort_key)
# Write countries.
match = re.match(r"(.*\nCOUNTRIES = \{\n)(.*?)(\n\}.*)", contents, re.DOTALL)
if not match:
raise ValueError('Expected a "COUNTRIES =" section in the source file!')
bits = match.groups()
country_list = []
for country_row in countries:
name = country_row[0].replace('"', r"\"").strip()
country_list.append(f' "{country_row[1]}": _("{name}"),')
content = bits[0]
content += "\n".join(country_list)
# Write alt codes.
alt_match = re.match(r"(.*\nALT_CODES = \{\n)(.*)(\n\}.*)", bits[2], re.DOTALL)
if not alt_match:
raise ValueError('Expected an "ALT_CODES =" section in the source file!')
alt_bits = alt_match.groups()
alt_list = []
for country_row in countries:
alt_list.append(
f' "{country_row[1]}": ("{country_row[2]}", {country_row[3]}),'
)
content += alt_bits[0]
content += "\n".join(alt_list)
content += alt_bits[2]
# Generate file.
with open(output_filename, "w") as output_file:
output_file.write(content)
return countries
def check_flags(verbosity: int = 1):
files = {}
this_dir = os.path.dirname(__file__)
for path in glob.glob(os.path.join(this_dir, "static", "flags", "*.gif")):
files[os.path.basename(os.path.splitext(path)[0]).upper()] = path
flags_missing = set(COUNTRIES) - set(files)
if flags_missing: # pragma: no cover
print("The following country codes are missing a flag:")
for code in sorted(flags_missing):
print(f" {code} ({COUNTRIES[code]})")
elif verbosity: # pragma: no cover
print("All country codes have flags. :)")
code_missing = set(files) - set(COUNTRIES)
# Special-case EU and __
for special_code in ("EU", "__"):
code_missing.discard(special_code)
if code_missing: # pragma: no cover
print("")
print("The following flags don't have a matching country code:")
for path in sorted(code_missing):
print(f" {path}")
def check_common_names() -> None:
common_names_missing = set(CountriesBase.COMMON_NAMES) - set(COUNTRIES)
if common_names_missing: # pragma: no cover
print("")
print("The following common names do not match an official country code:")
for code in sorted(common_names_missing):
print(f" {code}")
if __name__ == "__main__": # pragma: no cover
countries = self_generate(__file__)
print(f"Wrote {len(countries)} countries.")
print("")
check_flags()
check_common_names()
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1712005260.0
django-countries-7.6.1/django_countries/fields.py 0000644 0001750 0001751 00000044712 14602620214 021225 0 ustar 00chris chris import re
import sys
from typing import Any, Iterable, Optional, Tuple, Type, Union, cast
from urllib import parse as urlparse
import django
from django import forms
from django.contrib.admin.filters import FieldListFilter
from django.core import checks, exceptions
from django.db.models import lookups
from django.db.models.fields import BLANK_CHOICE_DASH, CharField
from django.utils.encoding import force_str
from django.utils.functional import lazy
from django.utils.html import escape as escape_html
from django_countries import Countries, countries, filters, ioc_data, widgets
from django_countries.conf import settings
_entry_points: Iterable[Any]
try:
import importlib.metadata
if sys.version_info >= (3, 10):
_entry_points = importlib.metadata.entry_points(
group="django_countries.Country"
)
else:
_entry_points = importlib.metadata.entry_points().get(
"django_countries.Country", []
)
except ImportError: # Python <3.8
import pkg_resources
_entry_points = pkg_resources.iter_entry_points("django_countries.Country")
EXTENSIONS = {ep.name: ep.load() for ep in _entry_points} # type: ignore
class TemporaryEscape:
__slots__ = ["country", "original_escape"]
def __init__(self, country):
self.country = country
def __bool__(self):
return self.country._escape
def __enter__(self):
self.original_escape = self.country._escape
self.country._escape = True
def __exit__(self, type, value, traceback):
self.country._escape = self.original_escape
class Country:
def __init__(
self,
code: str,
flag_url: Optional[str] = None,
str_attr: str = "code",
custom_countries: Optional[Countries] = None,
):
self.flag_url = flag_url
self._escape = False
self._str_attr = str_attr
if custom_countries is countries:
custom_countries = None
self.custom_countries = custom_countries
# Attempt to convert the code to the alpha2 equivalent, but this
# is not meant to be full validation so use the given code if no
# match was found.
self.code = self.countries.alpha2(code) or code
def __str__(self):
return force_str(getattr(self, self._str_attr) or "")
def __eq__(self, other):
return force_str(self.code or "") == force_str(other or "")
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(force_str(self))
def __repr__(self):
args = [f"code={self.code!r}"]
if self.flag_url is not None:
args.append(f"flag_url={self.flag_url!r}")
if self._str_attr != "code":
args.append(f"str_attr={self._str_attr!r}")
return f"{self.__class__.__name__}({', '.join(args)})"
def __bool__(self):
return bool(self.code)
def __len__(self):
return len(force_str(self))
@property
def countries(self):
return self.custom_countries or countries
@property
def escape(self):
return TemporaryEscape(self)
def maybe_escape(self, text) -> str:
return escape_html(text) if self.escape else text
@property
def name(self) -> str:
return self.maybe_escape(self.countries.name(self.code))
@property
def alpha3(self) -> str:
return self.countries.alpha3(self.code)
@property
def numeric(self) -> Optional[int]:
return self.countries.numeric(self.code)
@property
def numeric_padded(self) -> Optional[str]:
return self.countries.numeric(self.code, padded=True)
@property
def flag(self) -> str:
if not self.code:
return ""
flag_url = self.flag_url
if flag_url is None:
flag_url = settings.COUNTRIES_FLAG_URL
url = flag_url.format(code_upper=self.code, code=self.code.lower())
if not url:
return ""
url = urlparse.urljoin(settings.STATIC_URL, url)
return self.maybe_escape(url)
@property
def flag_css(self) -> str:
"""
Output the css classes needed to display an HTML element as a flag
sprite.
Requires the use of 'flags/sprite.css' or 'flags/sprite-hq.css'.
Usage example::
>> from people import Person
>>> person = Person.object.get(name='Chris')
>>> person.country.name
'New Zealand'
>>> person.country.flag
'/static/flags/nz.gif'
"""
def __init__(self, field):
self.field = field
def __get__(self, instance=None, owner=None):
if instance is None:
return self
# Check in case this field was deferred.
if self.field.name not in instance.__dict__:
instance.refresh_from_db(fields=[self.field.name])
value = instance.__dict__[self.field.name]
if self.field.multiple:
return [self.country(code) for code in value]
return self.country(value)
def country(self, code):
return Country(
code=code,
flag_url=self.field.countries_flag_url,
str_attr=self.field.countries_str_attr,
custom_countries=self.field.countries,
)
def __set__(self, instance, value):
value = self.field.get_clean_value(value)
instance.__dict__[self.field.name] = value
class LazyChoicesMixin(widgets.LazyChoicesMixin):
if django.VERSION < (5, 0):
def _set_choices(self, value):
"""
Also update the widget's choices.
"""
super()._set_choices(value)
self.widget.choices = value
_Choice = Tuple[Any, str]
_ChoiceNamedGroup = Tuple[str, Iterable[_Choice]]
_FieldChoices = Iterable[Union[_Choice, _ChoiceNamedGroup]]
class LazyTypedChoiceField(LazyChoicesMixin, forms.TypedChoiceField):
"""
A form TypedChoiceField that respects choices being a lazy object.
"""
choices: Any
widget = widgets.LazySelect
class LazyTypedMultipleChoiceField(LazyChoicesMixin, forms.TypedMultipleChoiceField):
"""
A form TypedMultipleChoiceField that respects choices being a lazy object.
"""
choices: Any
widget = widgets.LazySelectMultiple
class CountryField(CharField):
"""
A country field for Django models that provides all ISO 3166-1 countries as
choices.
"""
descriptor_class = CountryDescriptor
countries: Countries
def __init__(self, *args: Any, **kwargs: Any):
countries_class: Type[Countries] = kwargs.pop("countries", None)
self.countries = countries_class() if countries_class else countries
self.countries_flag_url = kwargs.pop("countries_flag_url", None)
self.countries_str_attr = kwargs.pop("countries_str_attr", "code")
self.blank_label = kwargs.pop("blank_label", None)
self.multiple = kwargs.pop("multiple", None)
self.multiple_unique = kwargs.pop("multiple_unique", True)
self.multiple_sort = kwargs.pop("multiple_sort", True)
if django.VERSION >= (5, 0):
# Use new lazy callable support
kwargs["choices"] = lambda: self.countries
else:
kwargs["choices"] = self.countries
if "max_length" not in kwargs:
# Allow explicit max_length so migrations can correctly identify
# changes in the multiple CountryField fields when new countries are
# added to the available countries dictionary.
if self.multiple:
kwargs["max_length"] = (
len(self.countries)
- 1
+ sum(len(code) for code in self.countries.countries)
)
else:
kwargs["max_length"] = max(
len(code) for code in self.countries.countries
)
super().__init__(*args, **kwargs)
def check(self, **kwargs):
errors = super().check(**kwargs)
errors.extend(self._check_multiple())
return errors
def _check_multiple(self):
if not self.multiple or not self.null:
return []
hint = "Remove null=True argument on the field"
if not self.blank:
hint += " (just add blank=True if you want to allow no selection)"
hint += "."
return [
checks.Error(
"Field specifies multiple=True, so should not be null.",
obj=self,
id="django_countries.E100",
hint=hint,
)
]
def get_internal_type(self):
return "CharField"
def contribute_to_class(self, cls, name):
super().contribute_to_class(cls, name)
setattr(cls, self.name, self.descriptor_class(self))
def pre_save(self, *args, **kwargs):
"Returns field's value just before saving."
value = super(CharField, self).pre_save(*args, **kwargs)
return self.get_prep_value(value)
def get_prep_value(self, value):
"Returns field's value prepared for saving into a database."
value = self.get_clean_value(value)
if self.multiple:
value = ",".join(value) if value else ""
return super(CharField, self).get_prep_value(value)
def country_to_text(self, value):
if hasattr(value, "code"):
value = value.code
if value is None:
return None
return force_str(value)
def get_clean_value(self, value):
if value is None:
return None
if not self.multiple:
return self.country_to_text(value)
if isinstance(value, (str, Country)):
if isinstance(value, str) and "," in value:
value = value.split(",")
else:
value = [value]
else:
try:
iter(value)
except TypeError:
value = [value]
cleaned_value = []
seen = set()
for c in value:
c = self.country_to_text(c)
if not c:
continue
if self.multiple_unique:
if c in seen:
continue
seen.add(c)
cleaned_value.append(c)
if self.multiple_sort:
cleaned_value = sorted(cleaned_value)
return cleaned_value
def deconstruct(self):
"""
Remove choices from deconstructed field, as this is the country list
and not user editable.
Not including the ``blank_label`` property, as this isn't database
related.
"""
name, path, args, kwargs = super(CharField, self).deconstruct()
kwargs.pop("choices", None)
if self.multiple: # multiple determines the length of the field
kwargs["multiple"] = self.multiple
if not self.multiple_unique:
kwargs["multiple_unique"] = False
if not self.multiple_sort:
kwargs["multiple_sort"] = False
if self.countries is not countries:
# Include the countries class if it's not the default countries
# instance.
kwargs["countries"] = self.countries.__class__
return name, path, args, kwargs
if django.VERSION >= (5, 0):
def get_choices(
self,
include_blank=True,
blank_choice=BLANK_CHOICE_DASH,
limit_choices_to=None,
ordering=(),
):
if self.multiple:
include_blank = False
if self.blank_label is None:
blank_choice = BLANK_CHOICE_DASH
else:
blank_choice = [("", self.blank_label)]
return super().get_choices(
include_blank=include_blank,
blank_choice=blank_choice,
limit_choices_to=limit_choices_to,
ordering=ordering,
)
else:
def get_choices( # type: ignore [misc]
self, include_blank=True, blank_choice=None, *args, **kwargs
):
if blank_choice is None:
if self.blank_label is None:
blank_choice = BLANK_CHOICE_DASH
else:
blank_choice = [("", self.blank_label)]
if self.multiple:
include_blank = False
return super().get_choices(
include_blank=include_blank, blank_choice=blank_choice, *args, **kwargs
)
get_choices = lazy(get_choices, list)
def formfield(self, **kwargs):
kwargs.setdefault(
"choices_form_class",
LazyTypedMultipleChoiceField if self.multiple else LazyTypedChoiceField,
)
if "coerce" not in kwargs:
kwargs["coerce"] = super().to_python
return super().formfield(**kwargs)
def to_python(self, value):
if not self.multiple:
return super().to_python(value)
if not value:
return value
if isinstance(value, str):
value = value.split(",")
output = []
for item in value:
output.append(super().to_python(item))
return output
def validate(self, value, model_instance):
"""
Use custom validation for when using a multiple countries field.
"""
if not self.multiple:
return super().validate(value, model_instance)
if not self.editable:
# Skip validation for non-editable fields.
return
if value:
choices = [option_key for option_key, option_value in self.choices]
for single_value in value:
if single_value not in choices:
raise exceptions.ValidationError(
self.error_messages["invalid_choice"],
code="invalid_choice",
params={"value": single_value},
)
if not self.blank and value in self.empty_values:
raise exceptions.ValidationError(self.error_messages["blank"], code="blank")
def value_to_string(self, obj):
"""
Ensure data is serialized correctly.
"""
value = self.value_from_object(obj)
return self.get_prep_value(value)
def get_lookup(self, lookup_name):
if not self.multiple and lookup_name in (
"contains",
"icontains",
"startswith",
"istartswith",
"endswith",
"iendswith",
"regex",
"iregex",
"name",
"iname",
):
lookup_name = f"country_{lookup_name}"
return super().get_lookup(lookup_name)
@CountryField.register_lookup
class ExactNameLookup(lookups.Exact):
lookup_name = "country_name"
insensitive: bool = False
def get_prep_lookup(self):
return cast(CountryField, self.lhs.output_field).countries.by_name(
force_str(self.rhs), insensitive=self.insensitive
)
def get_rhs_op(self, connection, rhs):
return connection.operators["exact"] % rhs
@CountryField.register_lookup
class IExactNameLookup(ExactNameLookup):
lookup_name = "country_iname"
insensitive: bool = True
class FullNameLookup(lookups.In):
expr: str
insensitive: bool = False
escape_regex: bool = True
def get_prep_lookup(self):
if isinstance(self.rhs, str):
value = self.expr.format(
text=re.escape(self.rhs) if self.escape_regex else self.rhs
)
options = cast(CountryField, self.lhs.output_field).countries.by_name(
value, regex=True, insensitive=self.insensitive
)
if len(self.rhs) == 2 and (
self.rhs == self.rhs.upper() or self.insensitive
):
options.add(self.rhs.upper())
return options
return super().get_prep_lookup() # pragma: no cover
@CountryField.register_lookup
class CountryContains(FullNameLookup):
lookup_name = "country_contains"
expr = r"{text}"
@CountryField.register_lookup
class CountryIContains(CountryContains):
lookup_name = "country_icontains"
insensitive = True
@CountryField.register_lookup
class CountryStartswith(FullNameLookup):
lookup_name = "country_startswith"
expr = r"^{text}"
@CountryField.register_lookup
class CountryIStartswith(CountryStartswith):
lookup_name = "country_istartswith"
insensitive = True
@CountryField.register_lookup
class CountryEndswith(FullNameLookup):
lookup_name = "country_endswith"
expr = r"{text}$"
@CountryField.register_lookup
class CountryIEndswith(CountryEndswith):
lookup_name = "country_iendswith"
insensitive = True
@CountryField.register_lookup
class CountryRegex(FullNameLookup):
lookup_name = "country_regex"
expr = r"{text}"
escape_regex = False
@CountryField.register_lookup
class CountryIRegex(CountryRegex):
lookup_name = "country_iregex"
insensitive = True
FieldListFilter.register(lambda f: isinstance(f, CountryField), filters.CountryFilter)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1712005260.0
django-countries-7.6.1/django_countries/filters.py 0000644 0001750 0001751 00000003010 14602620214 021411 0 ustar 00chris chris import django
from django.contrib import admin
from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _
class CountryFilter(admin.FieldListFilter):
"""
A country filter for Django admin that only returns a list of countries
related to the model.
"""
title = _("Country") # type: ignore
def expected_parameters(self):
return [self.field.name]
def choices(self, changelist):
value = self.used_parameters.get(self.field.name)
yield {
"selected": value is None,
"query_string": changelist.get_query_string({}, [self.field.name]),
"display": _("All"),
}
for lookup, title in self.lookup_choices(changelist):
if django.VERSION >= (5, 0):
selected = value is not None and force_str(lookup) in value
else:
selected = force_str(lookup) == value
yield {
"selected": selected,
"query_string": changelist.get_query_string(
{self.field.name: lookup}, []
),
"display": title,
}
def lookup_choices(self, changelist):
qs = changelist.model._default_manager.all()
codes = set(
qs.distinct()
.order_by(self.field.name)
.values_list(self.field.name, flat=True)
)
for k, v in self.field.get_choices(include_blank=False):
if k in codes:
yield k, v
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1712005260.714027
django-countries-7.6.1/django_countries/graphql/ 0000755 0001750 0001751 00000000000 14602620215 021034 5 ustar 00chris chris ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1712005260.0
django-countries-7.6.1/django_countries/graphql/__init__.py 0000644 0001750 0001751 00000000000 14602620214 023132 0 ustar 00chris chris ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1712005260.0
django-countries-7.6.1/django_countries/graphql/types.py 0000644 0001750 0001751 00000001612 14602620214 022551 0 ustar 00chris chris import graphene # type: ignore
class Country(graphene.ObjectType):
name = graphene.String(description="Country name")
code = graphene.String(description="ISO 3166-1 two character country code")
alpha3 = graphene.String(description="ISO 3166-1 three character country code")
numeric = graphene.Int(description="ISO 3166-1 numeric country code")
ioc_code = graphene.String(
description="International Olympic Committee country code"
)
@staticmethod
def resolve_name(country, info):
return country.name
@staticmethod
def resolve_code(country, info):
return country.code
@staticmethod
def resolve_alpha3(country, info):
return country.alpha3
@staticmethod
def resolve_numeric(country, info):
return country.numeric
@staticmethod
def resolve_ioc_code(country, info):
return country.ioc_code
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1712005260.0
django-countries-7.6.1/django_countries/ioc_data.py 0000644 0001750 0001751 00000013473 14602620214 021522 0 ustar 00chris chris IOC_TO_ISO = {
"AFG": "AF",
"ALB": "AL",
"ALG": "DZ",
"AND": "AD",
"ANG": "AO",
"ANT": "AG",
"ARG": "AR",
"ARM": "AM",
"ARU": "AW",
"ASA": "AS",
"AUS": "AU",
"AUT": "AT",
"AZE": "AZ",
"BAH": "BS",
"BAN": "BD",
"BAR": "BB",
"BDI": "BI",
"BEL": "BE",
"BEN": "BJ",
"BER": "BM",
"BHU": "BT",
"BIH": "BA",
"BIZ": "BZ",
"BLR": "BY",
"BOL": "BO",
"BOT": "BW",
"BRA": "BR",
"BRN": "BH",
"BRU": "BN",
"BUL": "BG",
"BUR": "BF",
"CAF": "CF",
"CAM": "KH",
"CAN": "CA",
"CAY": "KY",
"CGO": "CG",
"CHA": "TD",
"CHI": "CL",
"CHN": "CN",
"CIV": "CI",
"CMR": "CM",
"COD": "CD",
"COK": "CK",
"COL": "CO",
"COM": "KM",
"CPV": "CV",
"CRC": "CR",
"CRO": "HR",
"CUB": "CU",
"CYP": "CY",
"CZE": "CZ",
"DEN": "DK",
"DJI": "DJ",
"DMA": "DM",
"DOM": "DO",
"ECU": "EC",
"EGY": "EG",
"ERI": "ER",
"ESA": "SV",
"ESP": "ES",
"EST": "EE",
"ETH": "ET",
"FIJ": "FJ",
"FIN": "FI",
"FRA": "FR",
"FSM": "FM",
"GAB": "GA",
"GAM": "GM",
"GBR": "GB",
"GBS": "GW",
"GEO": "GE",
"GEQ": "GQ",
"GER": "DE",
"GHA": "GH",
"GRE": "GR",
"GRN": "GD",
"GUA": "GT",
"GUI": "GN",
"GUM": "GU",
"GUY": "GY",
"HAI": "HT",
"HKG": "HK",
"HON": "HN",
"HUN": "HU",
"INA": "ID",
"IND": "IN",
"IRI": "IR",
"IRL": "IE",
"IRQ": "IQ",
"ISL": "IS",
"ISR": "IL",
"ISV": "VI",
"ITA": "IT",
"IVB": "VG",
"JAM": "JM",
"JOR": "JO",
"JPN": "JP",
"KAZ": "KZ",
"KEN": "KE",
"KGZ": "KG",
"KIR": "KI",
"KOR": "KR",
"KSA": "SA",
"KUW": "KW",
"LAO": "LA",
"LAT": "LV",
"LBA": "LY",
"LBR": "LR",
"LCA": "LC",
"LES": "LS",
"LBN": "LB",
"LIE": "LI",
"LTU": "LT",
"LUX": "LU",
"MAD": "MG",
"MAR": "MA",
"MAS": "MY",
"MAW": "MW",
"MDA": "MD",
"MDV": "MV",
"MEX": "MX",
"MGL": "MN",
"MHL": "MH",
"MKD": "MK",
"MLI": "ML",
"MLT": "MT",
"MNE": "ME",
"MON": "MC",
"MOZ": "MZ",
"MRI": "MU",
"MTN": "MR",
"MYA": "MM",
"NAM": "NA",
"NCA": "NI",
"NED": "NL",
"NEP": "NP",
"NGR": "NG",
"NIG": "NE",
"NOR": "NO",
"NRU": "NR",
"NZL": "NZ",
"OMA": "OM",
"PAK": "PK",
"PAN": "PA",
"PAR": "PY",
"PER": "PE",
"PHI": "PH",
"PLE": "PS",
"PLW": "PW",
"PNG": "PG",
"POL": "PL",
"POR": "PT",
"PRK": "KP",
"PUR": "PR",
"QAT": "QA",
"ROU": "RO",
"RSA": "ZA",
"RUS": "RU",
"RWA": "RW",
"SAM": "WS",
"SEN": "SN",
"SEY": "SC",
"SKN": "KN",
"SLE": "SL",
"SLO": "SI",
"SMR": "SM",
"SGP": "SG",
"SOL": "SB",
"SOM": "SO",
"SRB": "RS",
"SRI": "LK",
"STP": "ST",
"SUD": "SD",
"SUI": "CH",
"SUR": "SR",
"SVK": "SK",
"SWE": "SE",
"SWZ": "SZ",
"SYR": "SY",
"TAN": "TZ",
"TGA": "TO",
"THA": "TH",
"TJK": "TJ",
"TKM": "TM",
"TLS": "TL",
"TOG": "TG",
"TPE": "TW",
"TTO": "TT",
"TUN": "TN",
"TUR": "TR",
"TUV": "TV",
"UAE": "AE",
"UGA": "UG",
"UKR": "UA",
"URU": "UY",
"USA": "US",
"UZB": "UZ",
"VAN": "VU",
"VEN": "VE",
"VIE": "VN",
"VIN": "VC",
"YEM": "YE",
"ZAM": "ZM",
"ZIM": "ZW",
}
IOC_HISTORICAL_TO_ISO = {
"AGR": "DZ",
"AGL": "DZ",
"BAD": "BB",
"DAY": "BJ",
"DAH": "BJ",
"BSH": "BA",
"HBR": "BZ",
"VOL": "BF",
"AFC": "CF",
"CAB": "KH",
"KHM": "KH",
"CHD": "TD",
"CIL": "CL",
"PRC": "CN",
"IVC": "CI",
"CML": "CI",
"COK": "CD",
"ZAI": "CD",
"COS": "CR",
"TCH": "CZ",
"DAN": "DK",
"DIN": "DK",
"RAU": "EG", # Used 1960, 1968 (also used by Syria in 1960)
"UAR": "EG",
"SAL": "SV",
"SPA": "ES",
"ETI": "ET",
"FIG": "FJ",
"GRB": "GB",
"GBI": "GB",
"ALL": "DE",
"ALE": "DE",
"GUT": "GT",
"GUA": "GY",
"GUI": "GY",
"HOK": "HK",
"UNG": "HU",
"INS": "ID",
"IRN": "IR",
"IRA": "IR",
"IRK": "IQ",
"ICE": "IS",
"ISL": "IL",
"GIA": "JP",
"JAP": "JP",
"COR": "KR",
"ARS": "SA",
"SAU": "SA",
"LYA": "LY",
"LBY": "LY",
"LEB": "LB", # Used from 1960-1964
"LIB": "LB", # Used from 1964-2016
"LIC": "LI",
"LIT": "LT",
"MAG": "MG",
"MRC": "MA",
"MAL": "MY",
"MLD": "MD",
"MOD": "MN",
"MAT": "MT",
"BIR": "MM",
"BUR": "MM",
"NGC": "NI",
"NIC": "NI",
"OLA": "NL",
"NET": "NL",
"NLD": "NL",
"HOL": "NL",
"NIG": "NG",
"NGA": "NG",
"NGR": "NE",
"NZE": "NZ",
"FIL": "PH",
"NGY": "PG",
"NGU": "PG",
"NKO": "KP",
"CDN": "KP",
"PRI": "PR",
"PRO": "PR",
"ROM": "RO",
"RUM": "RO",
"SAF": "ZA",
"SGL": "SN",
"SIN": "SG", # Used from 1959-2016
"SLA": "SL",
"SMA": "SM",
"CEY": "LK",
"CEI": "LK",
"SVI": "CH",
"SVE": "SE",
"SUE": "SE",
"SIR": "SY",
"TON": "TO",
"IOA": "TL",
"RCF": "TW",
"TWN": "TW",
"ROC": "TW",
"TRT": "TT",
"URG": "UY",
"SUA": "US",
"EUA": "US",
"VET": "VN",
"VNM": "VN",
"NRH": "ZM",
"RHO": "ZW",
}
ISO_TO_IOC = {iso: ioc for ioc, iso in IOC_TO_ISO.items()}
def check_ioc_countries(verbosity=1):
"""
Check if all IOC codes map to ISO codes correctly
"""
from django_countries.data import COUNTRIES
if verbosity: # pragma: no cover
print("Checking if all IOC codes map correctly")
for key in ISO_TO_IOC:
if not COUNTRIES.get(key): # pragma: no cover
raise KeyError(f"No ISO code for {key}")
if verbosity: # pragma: no cover
print("Finished checking IOC codes")
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1712005260.7106936
django-countries-7.6.1/django_countries/locale/ 0000755 0001750 0001751 00000000000 14602620215 020635 5 ustar 00chris chris ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1712005260.7073603
django-countries-7.6.1/django_countries/locale/af/ 0000755 0001750 0001751 00000000000 14602620215 021223 5 ustar 00chris chris ././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1712005260.714027
django-countries-7.6.1/django_countries/locale/af/LC_MESSAGES/ 0000755 0001750 0001751 00000000000 14602620215 023010 5 ustar 00chris chris ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1712005260.0
django-countries-7.6.1/django_countries/locale/af/LC_MESSAGES/django.mo 0000644 0001750 0001751 00000030662 14602620214 024615 0 ustar 00chris chris t g h i u }
( 0 8 ? E M T \ }
!
) 4 = F M \ u z &