2014-02-10 62 views
1

Django的localflavor貌似localflavor的一般用法是进口国的具体包:国际网站

from localflavor.nz.forms import NZRegionSelect

如果我有一个支持多个国家的网站?是否有一般代理是国家无关,是这样的:

from localflavor.autodetect.forms import RegionSelect

+0

一种选择是根据一些标准导入 - 如设置.. – karthikr

+0

@karthikr没错,我在想这个,但是在这个阶段我们不确定我们是否有基于位置的网络服务器。 –

回答

1

__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) 

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