{"id":13448807,"url":"https://github.com/SmileyChris/django-countries","last_synced_at":"2025-03-22T18:31:58.607Z","repository":{"id":639509,"uuid":"10851294","full_name":"SmileyChris/django-countries","owner":"SmileyChris","description":"A Django application that provides country choices for use with forms, flag icons static files, and a country field for models.","archived":false,"fork":false,"pushed_at":"2024-09-03T22:16:44.000Z","size":3587,"stargazers_count":1457,"open_issues_count":32,"forks_count":292,"subscribers_count":21,"default_branch":"main","last_synced_at":"2025-03-17T11:51:44.946Z","etag":null,"topics":["country-codes","django","python"],"latest_commit_sha":null,"homepage":"https://pypi.python.org/pypi/django-countries","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/SmileyChris.png","metadata":{"files":{"readme":"README.rst","changelog":"CHANGES.rst","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2013-06-21T20:02:58.000Z","updated_at":"2025-03-12T09:37:57.000Z","dependencies_parsed_at":"2024-05-01T12:25:03.484Z","dependency_job_id":"903608ba-aec0-4c20-b8ae-824794f33c81","html_url":"https://github.com/SmileyChris/django-countries","commit_stats":{"total_commits":617,"total_committers":54,"mean_commits":"11.425925925925926","dds":0.1701782820097245,"last_synced_commit":"f24637d32f08beed4941d452d3fef744f1594256"},"previous_names":[],"tags_count":58,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SmileyChris%2Fdjango-countries","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SmileyChris%2Fdjango-countries/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SmileyChris%2Fdjango-countries/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SmileyChris%2Fdjango-countries/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/SmileyChris","download_url":"https://codeload.github.com/SmileyChris/django-countries/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245002830,"owners_count":20545501,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["country-codes","django","python"],"created_at":"2024-07-31T06:00:21.558Z","updated_at":"2025-03-22T18:31:58.562Z","avatar_url":"https://github.com/SmileyChris.png","language":"Python","readme":"================\nDjango Countries\n================\n\n.. image:: https://badge.fury.io/py/django-countries.svg\n    :alt: PyPI version\n    :target: https://badge.fury.io/py/django-countries\n\n.. image:: https://github.com/SmileyChris/django-countries/actions/workflows/tests.yml/badge.svg\n    :alt: Build status\n    :target: https://github.com/SmileyChris/django-countries/actions/workflows/tests.yml\n\nA Django application that provides country choices for use with forms, flag\nicons static files, and a country field for models.\n\nCountry names are translated using Django's standard ``gettext``. If you would\nlike to help by adding a translation, please visit\nhttps://www.transifex.com/smileychris/django-countries/\n\n\n.. contents::\n    :local:\n    :backlinks: none\n\n\nInstallation\n============\n\n1. ``pip install django-countries``\n\n   For more accurate sorting of translated country names, install it with the\n   optional pyuca_ package:\n\n   ``pip install django-countries[pyuca]``\n\n2. Add ``django_countries`` to ``INSTALLED_APPS``\n\n.. _pyuca: https://pypi.python.org/pypi/pyuca/\n\n\nCountryField\n============\n\nA country field for Django models that provides all ISO 3166-1 countries as\nchoices.\n\n``CountryField`` is based on Django's ``CharField``, providing choices\ncorresponding to the official ISO 3166-1 list of countries (with a default\n``max_length`` of 2).\n\nConsider the following model using a ``CountryField``:\n\n.. code:: python\n\n    from django.db import models\n    from django_countries.fields import CountryField\n\n    class Person(models.Model):\n        name = models.CharField(max_length=100)\n        country = CountryField()\n\nAny ``Person`` instance will have a ``country`` attribute that you can use to\nget details of the person's country:\n\n.. code:: python\n\n    \u003e\u003e\u003e person = Person(name=\"Chris\", country=\"NZ\")\n    \u003e\u003e\u003e person.country\n    Country(code='NZ')\n    \u003e\u003e\u003e person.country.name\n    'New Zealand'\n    \u003e\u003e\u003e person.country.flag\n    '/static/flags/nz.gif'\n\nThis object (``person.country`` in the example) is a ``Country`` instance,\nwhich is described below.\n\nUse ``blank_label`` to set the label for the initial blank choice shown in\nforms:\n\n.. code:: python\n\n    country = CountryField(blank_label=\"(select country)\")\n\nYou can filter using the full English country names in addition to country\ncodes, even though only the country codes are stored in the database by using\nthe queryset lookups ``contains``, ``startswith``, ``endswith``, ``regex``, or\ntheir case insensitive versions. Use ``__name`` or ``__iname`` for the\n``exact``/``iexact`` equivalent:\n\n.. code:: python\n\n    \u003e\u003e\u003e Person.objects.filter(country__name=\"New Zealand\").count()\n    1\n    \u003e\u003e\u003e Person.objects.filter(country__icontains=\"zealand\").count()\n    1\n\n\nMulti-choice\n------------\n\nThis field can also allow multiple selections of countries (saved as a comma\nseparated string). The field will always output a list of countries in this\nmode. For example:\n\n.. code:: python\n\n    class Incident(models.Model):\n        title = models.CharField(max_length=100)\n        countries = CountryField(multiple=True)\n\n    \u003e\u003e\u003e for country in Incident.objects.get(title=\"Pavlova dispute\").countries:\n    ...     print(country.name)\n    Australia\n    New Zealand\n\nBy default, countries are stored sorted for data consistency, and any\nduplicates are removed. These behaviours can be overridden by using the field\narguments ``multiple_sort=False`` and ``multiple_unique=False`` respectively.\n\n\nThe ``Country`` object\n----------------------\n\nAn object used to represent a country, instantiated with a two character\ncountry code, three character code, or numeric code.\n\nIt can be compared to other objects as if it was a string containing the\ncountry code and when evaluated as text, returns the country code.\n\nname\n  Contains the full country name.\n\nflag\n  Contains a URL to the flag. If you page could have lots of different flags\n  then consider using ``flag_css`` instead to avoid excessive HTTP requests.\n\nflag_css\n  Output the css classes needed to display an HTML element as the correct flag\n  from within a single sprite image that contains all flags. For example:\n\n  .. code:: jinja\n\n    \u003clink rel=\"stylesheet\" href=\"{% static 'flags/sprite.css' %}\"\u003e\n    \u003ci class=\"{{ country.flag_css }}\"\u003e\u003c/i\u003e\n\n  For multiple flag resolutions, use ``sprite-hq.css`` instead and add the\n  ``flag2x``, ``flag3x``, or ``flag4x`` class. For example:\n\n  .. code:: jinja\n\n    \u003clink rel=\"stylesheet\" href=\"{% static 'flags/sprite-hq.css' %}\"\u003e\n    Normal: \u003ci class=\"{{ country.flag_css }}\"\u003e\u003c/i\u003e\n    Bigger: \u003ci class=\"flag2x {{ country.flag_css }}\"\u003e\u003c/i\u003e\n\n  You might also want to consider using ``aria-label`` for better\n  accessibility:\n\n  .. code:: jinja\n\n    \u003ci class=\"{{ country.flag_css }}\"\n        aria-label=\"{% blocktrans with country_code=country.code %}\n            {{ country_code }} flag\n        {% endblocktrans %}\"\u003e\u003c/i\u003e\n\nunicode_flag\n  A unicode glyph for the flag for this country. Currently well-supported in\n  iOS and OS X. See https://en.wikipedia.org/wiki/Regional_Indicator_Symbol\n  for details.\n\ncode\n  The two letter country code for this country.\n\nalpha3\n  The three letter country code for this country.\n\nnumeric\n  The numeric country code for this country (as an integer).\n\nnumeric_padded\n  The numeric country code as a three character 0-padded string.\n\nioc_code\n  The three letter International Olympic Committee country code.\n\n\n``CountrySelectWidget``\n-----------------------\n\nA widget is included that can show the flag image after the select box\n(updated with JavaScript when the selection changes).\n\nWhen you create your form, you can use this custom widget like normal:\n\n.. code:: python\n\n    from django_countries.widgets import CountrySelectWidget\n\n    class PersonForm(forms.ModelForm):\n        class Meta:\n            model = models.Person\n            fields = (\"name\", \"country\")\n            widgets = {\"country\": CountrySelectWidget()}\n\nPass a ``layout`` text argument to the widget to change the positioning of the\nflag and widget. The default layout is:\n\n.. code:: python\n\n    '{widget}\u003cimg class=\"country-select-flag\" id=\"{flag_id}\" style=\"margin: 6px 4px 0\" src=\"{country.flag}\"\u003e'\n\n\nCustom forms\n============\n\nIf you want to use the countries in a custom form, use the model field's custom\nform field to ensure the translatable strings for the country choices are left\nlazy until the widget renders:\n\n.. code:: python\n\n    from django_countries.fields import CountryField\n\n    class CustomForm(forms.Form):\n        country = CountryField().formfield()\n\nUse ``CountryField(blank=True)`` for non-required form fields, and\n``CountryField(blank_label=\"(Select country)\")`` to use a custom label for the\ninitial blank option.\n\nYou can also use the CountrySelectWidget_ as the widget for this field if you\nwant the flag image after the select box.\n\n\nGet the countries from Python\n=============================\n\nUse the ``django_countries.countries`` object instance as an iterator of ISO\n3166-1 country codes and names (sorted by name).\n\nFor example:\n\n.. code:: python\n\n    \u003e\u003e\u003e from django_countries import countries\n    \u003e\u003e\u003e dict(countries)[\"NZ\"]\n    'New Zealand'\n\n    \u003e\u003e\u003e for code, name in list(countries)[:3]:\n    ...     print(f\"{name} ({code})\")\n    ...\n    Afghanistan (AF)\n    Åland Islands (AX)\n    Albania (AL)\n\n\nTemplate Tags\n=============\n\nIf you have your country code stored in a different place than a\n``CountryField`` you can use the template tag to get a ``Country`` object and\nhave access to all of its properties:\n\n.. code:: jinja\n\n    {% load countries %}\n    {% get_country 'BR' as country %}\n    {{ country.name }}\n\nIf you need a list of countries, there's also a simple tag for that:\n\n.. code:: jinja\n\n    {% load countries %}\n    {% get_countries as countries %}\n    \u003cselect\u003e\n    {% for country in countries %}\n        \u003coption value=\"{{ country.code }}\"\u003e{{ country.name }}\u003c/option\u003e\n    {% endfor %}\n    \u003c/select\u003e\n\n\nCustomization\n=============\n\nCustomize the country list\n--------------------------\n\nCountry names are taken from the official ISO 3166-1 list, with some country\nnames being replaced with their more common usage (such as \"Bolivia\" instead\nof \"Bolivia, Plurinational State of\").\n\nTo retain the official ISO 3166-1 naming for all fields, set the\n``COUNTRIES_COMMON_NAMES`` setting to ``False``.\n\nIf your project requires the use of alternative names, the inclusion or\nexclusion of specific countries then set the ``COUNTRIES_OVERRIDE`` setting to\na dictionary of names which override the defaults. The values can also use a\nmore `complex dictionary format`_.\n\nNote that you will need to handle translation of customised country names.\n\nSetting a country's name to ``None`` will exclude it from the country list.\nFor example:\n\n.. code:: python\n\n    from django.utils.translation import gettext_lazy as _\n\n    COUNTRIES_OVERRIDE = {\n        \"NZ\": _(\"Middle Earth\"),\n        \"AU\": None,\n        \"US\": {\n            \"names\": [\n                _(\"United States of America\"),\n                _(\"America\"),\n            ],\n        },\n    }\n\nIf you have a specific list of countries that should be used, use\n``COUNTRIES_ONLY``:\n\n.. code:: python\n\n    COUNTRIES_ONLY = [\"NZ\", \"AU\"]\n\nor to specify your own country names, use a dictionary or two-tuple list\n(string items will use the standard country name):\n\n.. code:: python\n\n    COUNTRIES_ONLY = [\n        \"US\",\n        \"GB\",\n        (\"NZ\", _(\"Middle Earth\")),\n        (\"AU\", _(\"Desert\")),\n    ]\n\n\nShow certain countries first\n----------------------------\n\nProvide a list of country codes as the ``COUNTRIES_FIRST`` setting and they\nwill be shown first in the countries list (in the order specified) before all\nthe alphanumerically sorted countries.\n\nIf you want to sort these initial countries too, set the\n``COUNTRIES_FIRST_SORT`` setting to ``True``.\n\nBy default, these initial countries are not repeated again in the\nalphanumerically sorted list. If you would like them to be repeated, set the\n``COUNTRIES_FIRST_REPEAT`` setting to ``True``.\n\nFinally, you can optionally separate these \"first\" countries with an empty\nchoice by providing the choice label as the ``COUNTRIES_FIRST_BREAK`` setting.\n\n\nCustomize the flag URL\n----------------------\n\nThe ``COUNTRIES_FLAG_URL`` setting can be used to set the url for the flag\nimage assets. It defaults to:\n\n.. code:: python\n\n    COUNTRIES_FLAG_URL = \"flags/{code}.gif\"\n\nThe URL can be relative to the STATIC_URL setting, or an absolute URL.\n\nThe location is parsed using Python's string formatting and is passed the\nfollowing arguments:\n\n* ``code``\n* ``code_upper``\n\nFor example: ``COUNTRIES_FLAG_URL = \"flags/16x10/{code_upper}.png\"``\n\nNo checking is done to ensure that a static flag actually exists.\n\nAlternatively, you can specify a different URL on a specific ``CountryField``:\n\n.. code:: python\n\n    class Person(models.Model):\n        name = models.CharField(max_length=100)\n        country = CountryField(\n            countries_flag_url=\"//flags.example.com/{code}.png\")\n\n\nSingle field customization\n--------------------------\n\nTo customize an individual field, rather than rely on project level settings,\ncreate a ``Countries`` subclass which overrides settings.\n\nTo override a setting, give the class an attribute matching the lowercased\nsetting without the ``COUNTRIES_`` prefix.\n\nThen just reference this class in a field. For example, this ``CountryField``\nuses a custom country list that only includes the G8 countries:\n\n.. code:: python\n\n    from django_countries import Countries\n\n    class G8Countries(Countries):\n        only = [\n            \"CA\", \"FR\", \"DE\", \"IT\", \"JP\", \"RU\", \"GB\",\n            (\"EU\", _(\"European Union\"))\n        ]\n\n    class Vote(models.Model):\n        country = CountryField(countries=G8Countries)\n        approve = models.BooleanField()\n\n\nComplex dictionary format\n-------------------------\n\nFor ``COUNTRIES_ONLY`` and ``COUNTRIES_OVERRIDE``, you can also provide a\ndictionary rather than just a translatable string for the country name.\n\nThe options within the dictionary are:\n\n``name`` or ``names`` (required)\n  Either a single translatable name for this country or a list of multiple\n  translatable names. If using multiple names, the first name takes preference\n  when using ``COUNTRIES_FIRST`` or the ``Country.name``.\n\n``alpha3`` (optional)\n  An ISO 3166-1 three character code (or an empty string to nullify an existing\n  code for this country.\n\n``numeric`` (optional)\n  An ISO 3166-1 numeric country code (or ``None`` to nullify an existing code\n  for this country. The numeric codes 900 to 999 are left available by the\n  standard for user-assignment.\n\n``ioc_code`` (optional)\n  The country's International Olympic Committee code (or an empty string to\n  nullify an existing code).\n  \n\n``Country`` object external plugins\n-----------------------------------\n\nOther Python packages can add attributes to the Country_ object by using entry\npoints in their setup script.\n\n.. _Country: `The Country object`_\n\nFor example, you could create a ``django_countries_phone`` package which had a\nwith the following entry point in the ``setup.py`` file. The entry point name\n(``phone``) will be the new attribute name on the Country object. The attribute\nvalue will be the return value of the ``get_phone`` function (called with the\nCountry instance as the sole argument).\n\n.. code:: python\n\n  setup(\n      ...\n      entry_points={\n          \"django_countries.Country\": \"phone = django_countries_phone.get_phone\"\n      },\n      ...\n  )\n\n\n\nDjango Rest Framework\n=====================\n\nDjango Countries ships with a ``CountryFieldMixin`` to make the\n`CountryField`_ model field compatible with DRF serializers. Use the following\nmixin with your model serializer:\n\n.. code:: python\n\n    from django_countries.serializers import CountryFieldMixin\n\n    class CountrySerializer(CountryFieldMixin, serializers.ModelSerializer):\n\n        class Meta:\n            model = models.Person\n            fields = (\"name\", \"email\", \"country\")\n\nThis mixin handles both standard and `multi-choice`_ country fields.\n\n\nDjango Rest Framework field\n---------------------------\n\nFor lower level use (or when not dealing with model fields), you can use the\nincluded ``CountryField`` serializer field. For example:\n\n.. code:: python\n\n    from django_countries.serializer_fields import CountryField\n\n    class CountrySerializer(serializers.Serializer):\n        country = CountryField()\n\nYou can optionally instantiate the field with the ``countries`` argument to\nspecify a custom Countries_ instance.\n\n.. _Countries: `Single field customization`_\n\nREST output format\n^^^^^^^^^^^^^^^^^^\n\nBy default, the field will output just the country code. To output the full\ncountry name instead, instantiate the field with ``name_only=True``.\n\nIf you would rather have more verbose output, instantiate the field with\n``country_dict=True``, which will result in the field having the following\noutput structure:\n\n.. code:: json\n\n    {\"code\": \"NZ\", \"name\": \"New Zealand\"}\n\nEither the code or this dict output structure are acceptable as input\nirregardless of the ``country_dict`` argument's value.\n\n\nOPTIONS request\n---------------\n\nWhen you request OPTIONS against a resource (using the DRF `metadata support`_)\nthe countries will be returned in the response as choices:\n\n.. code:: text\n\n    OPTIONS /api/address/ HTTP/1.1\n\n    HTTP/1.1 200 OK\n    Content-Type: application/json\n    Allow: GET, POST, HEAD, OPTIONS\n\n    {\n    \"actions\": {\n      \"POST\": {\n        \"country\": {\n        \"type\": \"choice\",\n        \"label\": \"Country\",\n        \"choices\": [\n          {\n            \"display_name\": \"Australia\",\n            \"value\": \"AU\"\n          },\n          [...]\n          {\n            \"display_name\": \"United Kingdom\",\n            \"value\": \"GB\"\n          }\n        ]\n      }\n    }\n\n.. _metadata support: http://www.django-rest-framework.org/api-guide/metadata/\n\n\n\nGraphQL\n=======\n\nA ``Country`` graphene object type is included that can be used when generating\nyour schema.\n\n.. code:: python\n\n    import graphene\n    from graphene_django.types import DjangoObjectType\n    from django_countries.graphql.types import Country\n\n    class Person(ObjectType):\n        country = graphene.Field(Country)\n\n        class Meta:\n            model = models.Person\n            fields = [\"name\", \"country\"]\n\nThe object type has the following fields available:\n\n* ``name`` for the full country name\n* ``code`` for the ISO 3166-1 two character country code\n* ``alpha3`` for the ISO 3166-1 three character country code\n* ``numeric`` for the ISO 3166-1 numeric country code\n* ``iocCode`` for the International Olympic Committee country code\n","funding_links":[],"categories":["Fields","Geolocation","Python","资源列表","地理位置","Django Utilities","World Data (Countries, Cities, etc.)","Geolocation [🔝](#readme)","Awesome Python"],"sub_categories":["地理位置","More","Geolocation","Drone Frames"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FSmileyChris%2Fdjango-countries","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FSmileyChris%2Fdjango-countries","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FSmileyChris%2Fdjango-countries/lists"}