Skip to content

Instantly share code, notes, and snippets.

@paltman
Last active December 28, 2015 19:39
Show Gist options
  • Save paltman/7551838 to your computer and use it in GitHub Desktop.
Save paltman/7551838 to your computer and use it in GitHub Desktop.
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.forms.fields import Select
from django.utils import importlib
def load_path_attr(path):
i = path.rfind(".")
module, attr = path[:i], path[i+1:]
try:
mod = importlib.import_module(module)
except ImportError as e:
raise ImproperlyConfigured("Error importing {0}: '{1}'".format(module, e))
try:
attr = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured("Module '{0}' does not define a '{1}'".format(module, attr))
return attr
SUPPORTED_COUNTRIES = {
"US": {
"field": "localflavor.us.forms.USStateField",
"choices": "localflavor.us.us_states.STATE_CHOICES",
"label": "State"
}
}
class LocalFlavorPicker(object):
def __init__(self, country_code):
self.code = country_code
self.region_field = None
self.config = SUPPORTED_COUNTRIES.get(self.code.upper())
if self.config:
Field = load_path_attr(self.config["field"])
choices = [("", "---------")] + list(self.choices)
self.region_field = Field(
widget=Select(choices=choices),
required=False,
label=self.config["label"]
)
@property
def choices(self):
if self.config:
return load_path_attr(self.config["choices"])
return []
def assert_valid_region(self, region_code):
if self.choices and region_code not in self.choices:
raise ValidationError("{0} is an invalid region for {1}".format(
region_code,
self.code
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment