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

Overview

Django Countries

PyPI version Build status Coverage status

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

Installation

  1. pip install django-countries

    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

CountryField

A country field for Django models that provides all ISO 3166-1 countries as choices.

CountryField is based on Django's CharField, providing choices corresponding to the official ISO 3166-1 list of countries (with a default max_length of 2).

Consider the following model using a CountryField:

from django.db import models
from django_countries.fields import CountryField

class Person(models.Model):
    name = models.CharField(max_length=100)
    country = CountryField()

Any Person instance will have a country attribute that you can use to get details of the person's country:

>>> person = Person(name='Chris', country='NZ')
>>> person.country
Country(code='NZ')
>>> person.country.name
'New Zealand'
>>> person.country.flag
'/static/flags/nz.gif'

This object (person.country in the example) is a Country instance, which is described below.

Use blank_label to set the label for the initial blank choice shown in forms:

country = CountryField(blank_label='(select country)')

Multi-choice

This field can also allow multiple selections of countries (saved as a comma separated string). The field will always output a list of countries in this mode. For example:

class Incident(models.Model):
    title = models.CharField(max_length=100)
    countries = CountryField(multiple=True)

>>> for country in Incident.objects.get(title='Pavlova dispute').countries:
...     print(country.name)
Australia
New Zealand

The Country object

An object used to represent a country, instantiated with a two character country code, three character code, or numeric code.

It can be compared to other objects as if it was a string containing the country code and when evaluated as text, returns the country code.

name
Contains the full country name.
flag
Contains a URL to the flag. If you page could have lots of different flags then consider using flag_css instead to avoid excessive HTTP requests.
flag_css

Output the css classes needed to display an HTML element as the correct flag from within a single sprite image that contains all flags. For example:

<link rel="stylesheet" href="{% static 'flags/sprite.css' %}">
<i class="{{ country.flag_css }}"></i>

For multiple flag resolutions, use sprite-hq.css instead and add the flag2x, flag3x, or flag4x class. For example:

<link rel="stylesheet" href="{% static 'flags/sprite-hq.css' %}">
Normal: <i class="{{ country.flag_css }}"></i>
Bigger: <i class="flag2x {{ country.flag_css }}"></i>

You might also want to consider using aria-label for better accessibility:

<i class="{{ country.flag_css }}"
    aria-label="{% blocktrans with country_code=country.code %}
        {{ country_code }} flag
    {% endblocktrans %}"></i>
unicode_flag
A unicode glyph for the flag for this country. Currently well-supported in iOS and OS X. See https://en.wikipedia.org/wiki/Regional_Indicator_Symbol for details.
code
The two letter country code for this country.
alpha3
The three letter country code for this country.
numeric
The numeric country code for this country (as an integer).
numeric_padded
The numeric country code as a three character 0-padded string.
ioc_code
The three letter International Olympic Committee country code.

CountrySelectWidget

A widget is included that can show the flag image after the select box (updated with JavaScript when the selection changes).

When you create your form, you can use this custom widget like normal:

from django_countries.widgets import CountrySelectWidget

class PersonForm(forms.ModelForm):
    class Meta:
        model = models.Person
        fields = ('name', 'country')
        widgets = {'country': CountrySelectWidget()}

Pass a layout text argument to the widget to change the positioning of the flag and widget. The default layout is:

'{widget}<img class="country-select-flag" id="{flag_id}" style="margin: 6px 4px 0" src="{country.flag}">'

Custom forms

If you want to use the countries in a custom form, use the model field's custom form field to ensure the translatable strings for the country choices are left lazy until the widget renders:

from django_countries.fields import CountryField

class CustomForm(forms.Form):
    country = CountryField().formfield()

Use CountryField(blank=True) for non-required form fields, and CountryField(blank_label='(Select country)') to use a custom label for the initial blank option.

You can also use the CountrySelectWidget as the widget for this field if you want the flag image after the select box.

Get the countries from Python

Use the django_countries.countries object instance as an iterator of ISO 3166-1 country codes and names (sorted by name).

For example:

>>> from django_countries import countries
>>> dict(countries)['NZ']
'New Zealand'

>>> for code, name in list(countries)[:3]:
...     print(f"{name} ({code})")
...
Afghanistan (AF)
Åland Islands (AX)
Albania (AL)

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

Template Tags

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

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

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

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

Customization

Customize the country list

Country names are taken from the official ISO 3166-1 list, 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:

from django.utils.translation import gettext_lazy as _

COUNTRIES_OVERRIDE = {
    'NZ': _('Middle Earth'),
    'AU': None,
    'US': {'names': [
        _('United States of America'),
        _('America'),
    ],
}

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

COUNTRIES_ONLY = ['NZ', 'AU']

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

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

Show certain countries first

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

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

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

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

Customize the flag URL

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

COUNTRIES_FLAG_URL = 'flags/{code}.gif'

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

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

  • code
  • code_upper

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

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

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

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

Single field customization

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

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

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

from django_countries import Countries

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

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

Complex dictionary format

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

The options within the dictionary are:

name or names (required)
Either a single translatable name for this country or a list of multiple translatable names. If using multiple names, the first name takes preference when using COUNTRIES_FIRST or the Country.name.
alpha3 (optional)
An ISO 3166-1 three character code (or an empty string to nullify an existing code for this country.
numeric (optional)
An ISO 3166-1 numeric country code (or None to nullify an existing code for this country. The numeric codes 900 to 999 are left available by the standard for user-assignment.
ioc_code (optional)
The country's International Olympic Committee code (or an empty string to nullify an existing code).

Country object external plugins

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

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

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

Django Rest Framework

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

from django_countries.serializers import CountryFieldMixin

class CountrySerializer(CountryFieldMixin, serializers.ModelSerializer):

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

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

Django Rest Framework field

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

from django_countries.serializer_fields import CountryField

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

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

REST output format

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

If you would rather have more verbose output, instantiate the field with country_dict=True, which will result in the field having the following output structure:

{"code": "NZ", "name": "New Zealand"}

Either the code or this dict output structure are acceptable as input irregardless of the country_dict argument's value.

OPTIONS request

When you request OPTIONS against a resource (using the DRF metadata support) the countries will be returned in the response as choices:

OPTIONS /api/address/ HTTP/1.1

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

{
"actions": {
  "POST": {
    "country": {
    "type": "choice",
    "label": "Country",
    "choices": [
      {
        "display_name": "Australia",
        "value": "AU"
      },
      [...]
      {
        "display_name": "United Kingdom",
        "value": "GB"
      }
    ]
  }
}

GraphQL

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

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

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

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

The object type has the following fields available:

  • name for the full country name
  • code for the ISO 3166-1 two character country code
  • alpha3 for the ISO 3166-1 three character country code
  • numeric for the ISO 3166-1 numeric country code
  • iocCode for the International Olympic Committee country code
Comments
  • Field is not serializeable with Django Rest Framework

    Field is not serializeable with Django Rest Framework

    Hello,

    I have encountered an issues when working with the country field and Django Rest Framwork. If in the models we have a field that can be set to blank:

    country = CountryField(_('country'), blank=True, null=True, default='NL')
    

    when used as a normal field in the serializer I get an error that: TypeError: Country(code=u'') is not JSON serializable. This happens only when the country field is blank.

    It has been reported by someone else also on the django rest framework group. https://groups.google.com/forum/#!topic/django-rest-framework/3hrS2xr6BS0

    I am not sure exactly if this can be solved on the django rest framework side but thought to report it here also. It might be solved on the django-countries side.

    Thanks, Vlad

    opened by vladlep 30
  • no_translation_fallback eventually overwrites default fallback to empty when under the server is under high load

    no_translation_fallback eventually overwrites default fallback to empty when under the server is under high load

    The function no_translation_fallback defined here is used to override the default translation fallback (identity) to empty within a with block and then to restore the original value. Normally everything is okay, but when the server is under high load, a race condition may occur.

    What happens is more or less:

    1. catalog._fallback initialized to Default
    2. catalog._fallback = A; orig = Default
    3. catalog._fallback = B; orig = A # Problem starts here
    4. catalog._fallback = Default (from 2)
    5. catalog._fallback = A (from 3)
    6. catalog._fallback is now A instead of Default when idle.

    To fix this, no_translation_fallback needs some kind of mutex or needs to be reworked so that it is not swapping a global variable to local scope and back like that.

    This bug first appeared in 7.4.0 with the introduction of no_translation_fallback. Actually, why is even no_translation_fallback needed instead of the default identity?

    The bug can be reproduced by adding some slow debug code to the function and concurrently requesting sites from a django server that uses django-countries. I debugged it by changing the function to the following:

    @contextmanager
    def no_translation_fallback():
        if not settings.USE_I18N:
            yield
            return
        catalog = _trans.catalog()
        original_fallback = catalog._fallback
        catalog._fallback = EmptyFallbackTranslator()
    
        import sys
        print(f'!!!!! REPLACED FALLBACK from {id(original_fallback)} to {id(catalog._fallback)}', file=sys.stderr)
        import traceback
        traceback.print_stack()
    
        try:
            yield
        finally:
            print(f'!!!!! RESTORING FALLBACK {id(original_fallback)} to {id(catalog._fallback)}', file=sys.stderr)
            catalog._fallback = original_fallback
    

    The log I got was (comments after # are my edit):

    # ...
    !!!!! RESTORING FALLBACK 140706581130456 to 3051452141680
    # Note that 140706581130456 is the original
    !!!!! REPLACED FALLBACK from 140706581130456 to 3051452141680
    # ...
    !!!!! RESTORING FALLBACK 140706581130456 to 3051452141680
    !!!!! REPLACED FALLBACK from 140706581130456 to 3051452141680
    # ... (a few dozen of requests)
    !!!!! RESTORING FALLBACK 140706581130456 to 3051501356656
    2022-11-04 03:35:05,478 [INFO-D] "GET /ajax/sync/?_=1667528209942 HTTP/1.1" 200 41
    !!!!! REPLACED FALLBACK from 140706581130456 to 3051497763456
    # Note that the second replacing thinks that 3051497763456 is the original
    !!!!! REPLACED FALLBACK from 3051497763456 to 3051500062704 
    
      File "C:\...\pydev_monkey.py", line 798, in __call__
        ret = self.original_func(*self.args, **self.kwargs)
      File "C:\Python39\lib\threading.py", line 937, in _bootstrap
        self._bootstrap_inner()
      File "C:\Python39\lib\threading.py", line 980, in _bootstrap_inner
        self.run()
      File "C:\Python39\lib\threading.py", line 917, in run
        self._target(*self._args, **self._kwargs)
      File "C:\Python39\lib\socketserver.py", line 683, in process_request_thread
        self.finish_request(request, client_address)
      File "C:\Python39\lib\socketserver.py", line 360, in finish_request
        self.RequestHandlerClass(request, client_address, self)
      File "C:\Python39\lib\socketserver.py", line 747, in __init__
        self.handle()
      File "C:\...\venvs\lib\site-packages\django\core\servers\basehttp.py", line 204, in handle
        self.handle_one_request()
      File "C:\...\venvs\lib\site-packages\django\core\servers\basehttp.py", line 227, in handle_one_request
        handler.run(self.server.get_app())
      File "C:\Python39\lib\wsgiref\handlers.py", line 137, in run
        self.result = application(self.environ, self.start_response)
      File "C:\...\venvs\lib\site-packages\django\contrib\staticfiles\handlers.py", line 80, in __call__
        return self.application(environ, start_response)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\wsgi.py", line 131, in __call__
        response = self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\base.py", line 140, in get_response
        response = self._middleware_chain(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\middleware.py", line 58, in __call__
        response = toolbar.process_request(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\__init__.py", line 206, in process_request
        return self.get_response(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\timer.py", line 65, in process_request
        return super().process_request(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\__init__.py", line 206, in process_request
        return self.get_response(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\__init__.py", line 206, in process_request
        return self.get_response(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\headers.py", line 46, in process_request
        return super().process_request(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\__init__.py", line 206, in process_request
        return self.get_response(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\__init__.py", line 206, in process_request
        return self.get_response(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\__init__.py", line 206, in process_request
        return self.get_response(request)
      File "C:\...\venvs\lib\site-packages\template_profiler_panel\panels\template.py", line 250, in process_request
        response = super(TemplateProfilerPanel, self).process_request(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\__init__.py", line 206, in process_request
        return self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\whitenoise\middleware.py", line 60, in __call__
        response = self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "C:\...\venvs\lib\site-packages\django\views\generic\base.py", line 103, in view
        return self.dispatch(request, *args, **kwargs)
      File "C:\...\django_project\django_app\views.py", line 185, in dispatch
        request.user.full_clean()
      File "C:\...\venvs\lib\site-packages\django\db\models\base.py", line 1445, in full_clean
        self.clean_fields(exclude=exclude)
      File "C:\...\venvs\lib\site-packages\django\db\models\base.py", line 1497, in clean_fields
        setattr(self, f.attname, f.clean(raw_value, self))
      File "C:\...\venvs\lib\site-packages\django\db\models\fields\__init__.py", line 755, in clean
        self.validate(value, model_instance)
      File "C:\...\venvs\lib\site-packages\django_countries\fields.py", line 412, in validate
        return super().validate(value, model_instance)
      File "C:\...\venvs\lib\site-packages\django\db\models\fields\__init__.py", line 727, in validate
        for option_key, option_value in self.choices:
      File "C:\...\venvs\lib\site-packages\django_countries\__init__.py", line 347, in __iter__
        countries = tuple(
      File "C:\...\venvs\lib\site-packages\django_countries\__init__.py", line 275, in translate_code
        yield self.translate_pair(code, name)
      File "C:\...\venvs\lib\site-packages\django_countries\__init__.py", line 295, in translate_pair
        with no_translation_fallback():
      File "C:\Python39\lib\contextlib.py", line 119, in __enter__
        return next(self.gen)
      File "C:\...\venvs\lib\site-packages\django_countries\__init__.py", line 68, in no_translation_fallback
        traceback.print_stack()
    !!!!! RESTORING FALLBACK 140706581130456 to 3051500062704
    !!!!! REPLACED FALLBACK from 140706581130456 to 3051500062704
      File "C:\...\pydev_monkey.py", line 798, in __call__
        ret = self.original_func(*self.args, **self.kwargs)
      File "C:\Python39\lib\threading.py", line 937, in _bootstrap
        self._bootstrap_inner()
      File "C:\Python39\lib\threading.py", line 980, in _bootstrap_inner
        self.run()
      File "C:\Python39\lib\threading.py", line 917, in run
        self._target(*self._args, **self._kwargs)
      File "C:\Python39\lib\socketserver.py", line 683, in process_request_thread
        self.finish_request(request, client_address)
      File "C:\Python39\lib\socketserver.py", line 360, in finish_request
        self.RequestHandlerClass(request, client_address, self)
      File "C:\Python39\lib\socketserver.py", line 747, in __init__
        self.handle()
      File "C:\...\venvs\lib\site-packages\django\core\servers\basehttp.py", line 204, in handle
        self.handle_one_request()
      File "C:\...\venvs\lib\site-packages\django\core\servers\basehttp.py", line 227, in handle_one_request
        handler.run(self.server.get_app())
      File "C:\Python39\lib\wsgiref\handlers.py", line 137, in run
        self.result = application(self.environ, self.start_response)
      File "C:\...\venvs\lib\site-packages\django\contrib\staticfiles\handlers.py", line 80, in __call__
        return self.application(environ, start_response)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\wsgi.py", line 131, in __call__
        response = self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\base.py", line 140, in get_response
        response = self._middleware_chain(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\middleware.py", line 58, in __call__
        response = toolbar.process_request(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\__init__.py", line 206, in process_request
        return self.get_response(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\timer.py", line 65, in process_request
        return super().process_request(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\__init__.py", line 206, in process_request
        return self.get_response(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\__init__.py", line 206, in process_request
        return self.get_response(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\headers.py", line 46, in process_request
        return super().process_request(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\__init__.py", line 206, in process_request
        return self.get_response(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\__init__.py", line 206, in process_request
        return self.get_response(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\__init__.py", line 206, in process_request
        return self.get_response(request)
      File "C:\...\venvs\lib\site-packages\template_profiler_panel\panels\template.py", line 250, in process_request
        response = super(TemplateProfilerPanel, self).process_request(request)
      File "C:\...\venvs\lib\site-packages\debug_toolbar\panels\__init__.py", line 206, in process_request
        return self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\whitenoise\middleware.py", line 60, in __call__
        response = self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\utils\deprecation.py", line 136, in __call__
        response = response or self.get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
        response = get_response(request)
      File "C:\...\venvs\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "C:\...\venvs\lib\site-packages\django\views\generic\base.py", line 103, in view
        return self.dispatch(request, *args, **kwargs)
      File "C:\...\django_project\django_app\views.py", line 185, in dispatch
        request.user.full_clean()
      File "C:\...\venvs\lib\site-packages\django\db\models\base.py", line 1445, in full_clean
        self.clean_fields(exclude=exclude)
      File "C:\...\venvs\lib\site-packages\django\db\models\base.py", line 1497, in clean_fields
        setattr(self, f.attname, f.clean(raw_value, self))
      File "C:\...\venvs\lib\site-packages\django\db\models\fields\__init__.py", line 755, in clean
        self.validate(value, model_instance)
      File "C:\...\venvs\lib\site-packages\django_countries\fields.py", line 412, in validate
        return super().validate(value, model_instance)
      File "C:\...\venvs\lib\site-packages\django\db\models\fields\__init__.py", line 727, in validate
        for option_key, option_value in self.choices:
      File "C:\...\venvs\lib\site-packages\django_countries\__init__.py", line 347, in __iter__
        countries = tuple(
      File "C:\...\venvs\lib\site-packages\django_countries\__init__.py", line 275, in translate_code
        yield self.translate_pair(code, name)
      File "C:\...\venvs\lib\site-packages\django_countries\__init__.py", line 295, in translate_pair
        with no_translation_fallback():
      File "C:\Python39\lib\contextlib.py", line 119, in __enter__
        return next(self.gen)
      File "C:\...\venvs\lib\site-packages\django_countries\__init__.py", line 68, in no_translation_fallback
        traceback.print_stack()
    # This is where the bug occurs - from now on 3051497763456 is the default fallback
    !!!!! RESTORING FALLBACK 3051497763456 to 3051500062704
    
    # All hell breaks loose here...
    
    opened by xi42 20
  • Add support for the upcoming Django 3.2

    Add support for the upcoming Django 3.2

    The CountryField uses super() in a few methods to skip CharField's methods and call methods of the CharField's superclass directly. Django 3.2 adds support for db_collation to CharField, but the CountryField doesn't need this. Since CountryField.__init__ does not call CharField.__init__, CountryField.deconstruct shouldn't call CharField.deconstruct either.

    Also, Django 3.1 and django-rest-framework 3.10.x are not compatible because django-rest-framework imports the FieldDoesNotExist exception from location where it isn't available anymore in Django 3.1. Therefore, this pull request also removes this combination from the CI matrix.

    Replaces #328

    opened by matthiask 10
  • Deprecate Python 2 and Django 1.x, add Django 3.0, DRF 3.10/11 support

    Deprecate Python 2 and Django 1.x, add Django 3.0, DRF 3.10/11 support

    Overlaps with #279 , #285, #286, #287, #290 in preparing for Django 3 and deprecating Python 2.


    This is intended as a prototype to demonstrate what django-countries would look like if it dropped support for Python 2 and Django 1.x when moving to Django 3 support (I totally understand @SmileyChris' desire to continue to support legacy versions, and am happy for the PR to be closed without merging) - its main purpose is discussion / reference.

    One thing that worth pointing out is the Django <> DRF test matrix. In version 3.7/8/9 DRF relies on the Django vendored version of six which was dropped in Django 3.0. Hence specifying DRF 3.10/11 for the Django 3.0 tests.

    | Python | Django 2.2 | Django 3.0 | |---|:--|:--| | 3.5 | DRF: 3.7, 3.8 | n/a | | 3.6 | DRF: 3.7, 3.8, 3.9 | 3.10, 3.11 | | 3.7 | DRF: 3.7, 3.8, 3.9 | 3.10, 3.11 | | 3.8 | DRF: 3.7, 3.8, 3.9 | 3.10, 3.11 |

    Changes

    • Remove use of six across the project
    • Replace force_text with force_str
    • Remove conditional Py2/3 import statements in favour of Py3 only
    • Replace mock with unittest.mock
    • Update super(Klass, self) to super() syntax
    • Remove __future__.unicode_literals imports
    • Update tox test configuration
    • Update travis CI configuration
    • Update classifiers in setup.cfg
    • Replace ugettext with gettext (deprecated in Django 4.0, and already just an alias)
    opened by hugorodgerbrown 10
  • Capitalization and diacritics in some country names

    Capitalization and diacritics in some country names

    While comparing the names of countries in the lists with those from iso-codes (http://packages.debian.org/iso-codes) I found some minor differences that should be fixed.

    The attached patch fixes all differences that I could find and for the record, those were my references:

    • http://www.nationsonline.org/oneworld/cote_d_ivoire.htm
    • http://www.nationsonline.org/oneworld/guinea_bissau.htm
    • http://www.vlada.mk/?language=en-gb
    • http://www.nationsonline.org/oneworld/reunion.htm
    • http://www.tristandc.com/
    • http://www.nationsonline.org/oneworld/timor_leste.htm

    • Bitbucket: https://bitbucket.org/smileychris/django-countries/issue/16
    • Originally Reported By: FladischerMichael
    • Originally Created At: 2011-10-30 23:39:52
    opened by SmileyChris 10
  • With DRF and depth > 1, got

    With DRF and depth > 1, got "Object of type 'Country' is not JSON serializable"

    So, I have a model of Service and Participant (this one has country), and the Service contains Participant.

    I'm using on my serializer:

    class ParticipantSerializer(serializers.ModelSerializer, CountryFieldMixin):
    
        class Meta:
            model = Participant
            fields = ('__all__')
    
    
    class ServiceSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = Service
            fields = ('__all__')
            depth = 1
    

    When I do a GET to /service:

    TypeError at /api/v1/service/
    Object of type 'Country' is not JSON serializable
    

    I'm using: Python 3.6 Django 2.0.8 djangorestframework 3.8.2 django-countries 5.3.2

    What am I missing?

    Thanks!

    opened by felipewove 9
  • Required Attribute Missing from CountrySelectWidget for Required CountryFields when COUNTRIES_FIRST_BREAK Setting Turned On

    Required Attribute Missing from CountrySelectWidget for Required CountryFields when COUNTRIES_FIRST_BREAK Setting Turned On

    When blank=True is not set on the CountryField of a model, the corresponding CountrySelectWidget in the ModelForm should render the select element with a required attribute.

    Python version: 3.5.2 Django version: 1.11.4

    opened by verngutz 9
  • Better sorting

    Better sorting

    I added unicode-aware sorting. For example, Latvia is translated in Polish to Łotwa. Diacritic Ł letter in Polish alphabet appears after L letter, but default python sorted function is ASCII only, so Łotwa will be added at the end of list (after all countries starting at Z). It does not require additional setup, but python locale.setlocale function is platform dependent. E. g. if you have set LANGUAGE_CODE = "en_us" and you are running Linux you need to use Linux language format, LANGUAGE_CODE = en_us.UTF-8. Django works fine with this format. Alternatively, if you don't like that sorting require adjusting LANGUAGE_CODE it can be added to django_countries specific settings.

    opened by fenuks 9
  • Different country choices for different model fields

    Different country choices for different model fields

    For a website I need to limit the country choices on a per-field basis. The usual way of using the COUNTRIES_ONLY setting does not work here.

    Example: A phone provider that has customers in the US and Canada, and allows calls to US, Canada and also the UK wants to log all calls:

    class Call(models.Model):
        customer = models.ForeignKey(Customer)
        calling_from = CountryField(choices=[
            ("US", _("United States of America")), ("CA", _("Canada"))]
        calling_to = CountryField(choices=[
            ("US", _("United States of America")), ("CA", _("Canada")),
            ("UK", _("United Kingdom and Northern Ireland"))]
    

    Unfortunately this also doesn't work, because the choices kwarg is always overwritten with the full list of countries.

    Do you think that only setting the choices kwarg when it is unset would be ok or is there some other code that depends on it?

    opened by soult 8
  • Option to Suppress Flag from CountrySelectWidget

    Option to Suppress Flag from CountrySelectWidget

    Hello. I want your list of countries in a select field in my Django form, but I do not want the tag with the flag in it. Can you add a boolean to suppress that rendered tag? Right now, I am doing that with Javascript.

    opened by mmangione 8
  • Add ability to query by country name

    Add ability to query by country name

    It would be nice to be able to do this so I don't need to add yet another package to get that functionality. Is there any interest in a pull request with this functionality?

    opened by jschneier 8
  • Queryset field lookups for country code no longer works as of 7.3

    Queryset field lookups for country code no longer works as of 7.3

    The change in 7.3, Make full English country names work in database lookups, for example, Person.objects.filter(country__icontains="zealand") has caused queryset filter field lookups for the two character country code to no longer work.

    For example, queryset.filter(country__regex=rf"^GB$") would return results from my DB in 7.2.1, but in 7.3 and later it returns an empty queryset. I also tested that queryset.filter(country__contains="GB") also incorrectly returns an empty queryset. However, queryset.filter(country="GB") works as expected and so does queryset.filter(country__contains="Kingdom")

    enhancement 
    opened by chenyaoy 1
  • django_countries 7.5 missing dependency on asgiref

    django_countries 7.5 missing dependency on asgiref

    $ virtualenv /tmp/countries
    created virtual environment CPython3.10.9.final.0-64 in 289ms
      creator CPython3Posix(dest=/tmp/countries, clear=False, no_vcs_ignore=False, global=False)
      seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/terceiro/.local/share/virtualenv)
        added seed packages: pip==22.3.1, setuptools==65.5.0, wheel==0.38.4
      activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator
    $ . /tmp/countries/bin/activate
    $ pip install django_countries
    Collecting django_countries
      Downloading django_countries-7.5-py3-none-any.whl (842 kB)
         ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 843.0/843.0 kB 1.3 MB/s eta 0:00:00
    Collecting typing-extensions
      Downloading typing_extensions-4.4.0-py3-none-any.whl (26 kB)
    Installing collected packages: typing-extensions, django_countries
    Successfully installed django_countries-7.5 typing-extensions-4.4.0
    $ python -c 'import django_countries'
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/countries/lib/python3.10/site-packages/django_countries/__init__.py", line 22, in <module>
        from asgiref.local import Local
    ModuleNotFoundError: No module named 'asgiref'
    
    bug 
    opened by terceiro 1
  • Further type hints

    Further type hints

    I'm rolling out Mypy's strict mode on a project, and the type hints in django-countries are triggering some errors. Specifically from activating the disallow_untyped_calls flag, which requires typed contexts only call typed functions, triggering errors like:

    example/core/models.py:112: error: Call to untyped function "CountryField" in typed context  [no-untyped-call]
    

    This is because, whilst django-countries has a py.typed file, CountryField.__init__ is not fully type hinted - the same for the other hints.

    Would you be interested in a PR that enables strict mode within django-countries' Mypy env, and expands the type hints?

    opened by adamchainz 1
  • Correct field to use in Admin form when multi=True

    Correct field to use in Admin form when multi=True

    Although there's stuff in the README about custom forms and the custom widgets, I couldn't see anything about what to do if you're using multi=True. I've got it working, but I'm not sure if this is the best way.

    I have this model:

    from django.db import models
    from django_countries.fields import CountryField
    
    class Person(models.Model):
        countries = CountryField(multiple=True, blank=True)
    

    And then in admin.py:

    from django import forms
    from django.contrib.admin.widgets import FilteredSelectMultiple
    from django_countries import countries as countries_object
    from .models import Person
    
    class PersonForm(forms.ModelForm):
        class Meta:
            model = Person
            exclude = ()
    
        countries = forms.MultipleChoiceField(
            choices=list(countries_object),
            widget=FilteredSelectMultiple("countries", is_stacked=False),
            required=False,
        )
    

    The choices is the bit I'm least sure about.

    If it is the best way then maybe something could be added to the README to help the next person who's confused?

    opened by philgyford 0
The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

null 4.6k Jan 7, 2023
django-quill-editor makes Quill.js easy to use on Django Forms and admin sites

django-quill-editor django-quill-editor makes Quill.js easy to use on Django Forms and admin sites No configuration required for static files! The ent

lhy 139 Dec 5, 2022
MAC address Model Field & Form Field for Django apps

django-macaddress MAC Address model and form fields for Django We use netaddr to parse and validate the MAC address. The tests aren't complete yet. Pa

null 49 Sep 4, 2022
A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for quickly creating new images from the one assigned to the field.

django-versatileimagefield A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for creat

Jonathan Ellenberger 490 Dec 13, 2022
Django-Audiofield is a simple app that allows Audio files upload, management and conversion to different audio format (mp3, wav & ogg), which also makes it easy to play audio files into your Django application.

Django-Audiofield Description: Django Audio Management Tools Maintainer: Areski Contributors: list of contributors Django-Audiofield is a simple app t

Areski Belaid 167 Nov 10, 2022
Money fields for Django forms and models.

django-money A little Django app that uses py-moneyed to add support for Money fields in your models and forms. Django versions supported: 1.11, 2.1,

null 1.4k Jan 6, 2023
Organize Django settings into multiple files and directories. Easily override and modify settings. Use wildcards and optional settings files.

Organize Django settings into multiple files and directories. Easily override and modify settings. Use wildcards in settings file paths and mark setti

Nikita Sobolev 940 Jan 3, 2023
Use webpack to generate your static bundles without django's staticfiles or opaque wrappers.

django-webpack-loader Use webpack to generate your static bundles without django's staticfiles or opaque wrappers. Django webpack loader consumes the

null 2.4k Dec 24, 2022
Django-static-site - A simple content site framework that harnesses the power of Django without the hassle

coltrane A simple content site framework that harnesses the power of Django with

Adam Hill 57 Dec 6, 2022
A set of high-level abstractions for Django forms

django-formtools Django's "formtools" is a set of high-level abstractions for Django forms. Currently for form previews and multi-step forms. This cod

Jazzband 621 Dec 30, 2022
django Filer is a file management application for django that makes handling of files and images a breeze.

django Filer is a file management application for django that makes handling of files and images a breeze.

django CMS Association 1.6k Jan 6, 2023
Location field and widget for Django. It supports Google Maps, OpenStreetMap and Mapbox

django-location-field Let users pick locations using a map widget and store its latitude and longitude. Stable version: django-location-field==2.1.0 D

Caio Ariede 481 Dec 29, 2022
A django model and form field for normalised phone numbers using python-phonenumbers

django-phonenumber-field A Django library which interfaces with python-phonenumbers to validate, pretty print and convert phone numbers. python-phonen

Stefan Foulis 1.3k Dec 31, 2022
A django model and form field for normalised phone numbers using python-phonenumbers

django-phonenumber-field A Django library which interfaces with python-phonenumbers to validate, pretty print and convert phone numbers. python-phonen

Stefan Foulis 1.3k Dec 31, 2022
django-reversion is an extension to the Django web framework that provides version control for model instances.

django-reversion django-reversion is an extension to the Django web framework that provides version control for model instances. Requirements Python 3

Dave Hall 2.8k Jan 2, 2023
A reusable Django model field for storing ad-hoc JSON data

jsonfield jsonfield is a reusable model field that allows you to store validated JSON, automatically handling serialization to and from the database.

Ryan P Kilby 1.1k Jan 3, 2023
Custom Django field for using enumerations of named constants

django-enumfield Provides an enumeration Django model field (using IntegerField) with reusable enums and transition validation. Installation Currently

5 Monkeys 195 Dec 20, 2022
A pickled object field for Django

django-picklefield About django-picklefield provides an implementation of a pickled object field. Such fields can contain any picklable objects. The i

Gintautas Miliauskas 167 Oct 18, 2022
A pickled object field for Django

django-picklefield About django-picklefield provides an implementation of a pickled object field. Such fields can contain any picklable objects. The i

Gintautas Miliauskas 167 Oct 18, 2022