Source code for superdjango.contrib.i18n.countries.forms

# Imports

from django import forms
from django.conf import settings
from .choices import SUB_REGION_COUNTRY_CHOICES

# Exports

__all__ = (
    "CountryField",
)

# Constants

DEFAULT_COUNTRY = getattr(settings, "SUPERDJANGO_I18N_DEFAULT_COUNTRY_CODE", None)

# Fields


[docs]class CountryField(forms.ChoiceField): """Provide country choices."""
[docs] def __init__(self, **kwargs): """``choices`` defaults to ``SUB_REGION_COUNTRY_CHOICES``, and ``initial`` defaults to ``SUPERDJANGO_I18N_DEFAULT_COUNTRY_CODE`` if defined in settings. """ # HACK: Django adds empty_value and max_length when specifying a country as a CharField and formfield() is # called for ChoiceField. This results in an __init__() error. I'm not sure if this is a safe or valid hack, but # it seems to work for the purpose of supplying choices at the form field level rather than to the model, which # is what we want to accomplish to avoid migrations and allow countries to be specified at runtime. if 'empty_value' in kwargs: del(kwargs['empty_value']) if 'max_length' in kwargs: del(kwargs['max_length']) kwargs.setdefault("choices", SUB_REGION_COUNTRY_CHOICES) # BUG: No matter what I do, the initial value for CountryField is ignored. kwargs.setdefault("initial", DEFAULT_COUNTRY) super().__init__(**kwargs)