Last active
December 28, 2015 19:39
-
-
Save paltman/7551838 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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