django localflavor for international site

416 Views Asked by At

Looks like the general usage of localflavor is import the country specific package:

from localflavor.nz.forms import NZRegionSelect

What if I have a site that supports multiple countries? Is there generic proxy to be country agnostic, something like:

from localflavor.autodetect.forms import RegionSelect

1

There are 1 best solutions below

0
On

__import__ would do the trick:

def get_region_select(country_code):
    module_path = 'django.contrib.localflavor.{}'.format(country_code)
    try:
        module = __import__(module_path, fromlist=['forms'])
    except ImportError:
        return None

    fieldname = '{}RegionSelect'.format(country_code.upper())
    if hasattr(module.forms, fieldname):
        return getattr(module.forms, fieldname)()
    return None

Adapted from: http://codeinthehole.com/writing/validating-international-postcodes-in-django/

Then, in your template you'll have to reload the page each time you change the country, and do something like this in the view:

form.fields['region'].widget = get_region_select(country)

Since different regions will have different choices.