系统日期格式不使用Django语言环境 [英] System date formatting not using django locale

查看:67
本文介绍了系统日期格式不使用Django语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图了解L10N在Django中的实现,这是我的设置

Trying to understand L10N implementation into Django, Here are my settings

LANGUAGE_CODE = 'fr-FR'
USE_L10N = True

如果我尝试

>>> datetime.datetime.strptime('2012-05-30 15:30', '%Y-%m-%d %H:%M')
      .strftime('%c')

它将为我提供'Wed May 30 15:30:00 2012',即 EN 语言环境.但是 doc 的意思是:

It will give me 'Wed May 30 15:30:00 2012' that is the EN locale. However the doc is saying:

[...]访问相同内容但使用不同语言的两个用户将看到日期和数字字段的格式不同,具体取决于其当前语言环境的格式[...]

[...] Two users accessing the same content, but in different language, will see date and number fields formatted in different ways, depending on the format for their current locale [...]

他们在谈论各自浏览器的语言环境设置吗?
如果没有,例如,如何默认将其设置为法语?

Are they talking about the locale set for their respective browser ?
If not, how can I set it to french by default for example ?

推荐答案

Django的本地化工作在Django模板和表单的上下文中进行,并且无法沿链条移动到Python的内部日期时间表示形式:

Django's localization works in the context of Django templates and forms, and can not travel up the chain to Python's internal datetime representations:

When using Django's formatting system, dates and numbers on templates 
will be displayed using the format specified for the current locale. 
...Django will also use localized formats when parsing data in forms. 

因此,如果您具有USE_L10N = True,并且区域为FR的用户将10,45输入一种形式,那么它将在英语十进制系统中被解释为表示10.45.同样,{{ value|date:"SHORT_DATE_FORMAT" }}之类的模板标签的输出将根据用户的语言环境而变化.

So if you have USE_L10N = True and a user with the region FR enters 10,45 into a form, that will be interpreted to mean 10.45 in the English decimal system. Similarly, the output of a template tag like {{ value|date:"SHORT_DATE_FORMAT" }} will vary based on the user's locale.

但是,Python内部的strftime('%c')不访问Django的设置,而是引用安装它的计算机上的语言环境设置.您可以使用以下方法检索和更改Python指向的语言环境设置:

However, the Python internal strftime('%c') doesn't access Django's settings, and instead refers to the locale set on the machine on which it is installed. You can retrieve and change the locale settings Python points to with:

>>> datetime.datetime.strptime('2012-05-30 15:30', '%Y-%m-%d %H:%M').strftime('%c')
'Wed May 30 15:30:00 2012'
>>> import locale
>>> locale.getlocale()
(None, None)
>>> locale.getdefaultlocale()
('en_US', 'UTF-8')
>>> locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
'fr_FR.UTF-8'
>>> datetime.datetime.strptime('2012-05-30 15:30', '%Y-%m-%d %H:%M').strftime('%c')
'Mer 30 mai 15:30:00 2012'

或通过设置环境变量$LANG.

这篇关于系统日期格式不使用Django语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆