2

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

4

1 回答 1

3

__import__可以解决问题:

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

改编自:http ://codeinthehole.com/writing/validating-international-postcodes-in-django/

然后,在您的模板中,每次更改国家/地区时都必须重新加载页面,并在视图中执行以下操作:

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

由于不同的地区会有不同的选择。

于 2014-05-01T05:04:07.720 回答