Linux和Windows上的Django语言环境设置,用于数字格式化

时间:2011-03-14 18:02:13

标签: python django locale

我有一个Django自定义模板标记

@register.filter("numformat")  
@stringfilter
def numformat(value, uLocale=''): 
    if uLocale.count('%') > 0 :
        return str((float(value)) *100) + "%"
    uLocale = uLocale.encode('utf8').strip("%")
    try :
        locale.setlocale(locale.LC_ALL, uLocale)
    except :
        return str(locale.format('%f',float(value), True)) + ' Unknown loacale '+uLocale
        locale.setlocale(locale.LC_ALL, "")
    return str(locale.format('%f',float(value), True)) + ' in loacale '+uLocale

它在模板文件中调用,如

{% if val_i.NumberFormat %}
    {{ val_i.value|urldecode|numformat:val_i.NumberFormat }}
{% else %}
    {{ val_i.value|urldecode }}
{% endif %}

val_i.NumberFormat的值是:

    Windows

  • deu_deu Linux

  • de_DE

问题是代码仅适用于 Windows ,而不适用于 Linux 。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

使用setlocale()这种方式可能会有问题,特别是因为线程(IIRC,setlocale()应用于程序范围,应该在生成新线程之前调用)。 babel(http://babel.edgewall.org/)完成了你想要实现的目标,并与Django合作。